diff options
author | Sviatoslav Sydorenko <wk@sydorenko.org.ua> | 2016-09-08 16:12:31 +0300 |
---|---|---|
committer | Sviatoslav Sydorenko <wk@sydorenko.org.ua> | 2016-09-08 16:12:31 +0300 |
commit | dc574c422886d192b33a48b036d0e9839c3cc6e0 (patch) | |
tree | c2f25676df9d99ee26521367aa1e01692d788a86 /cherrypy | |
parent | 2035500ef638a079665a29548aea74761d8877ef (diff) | |
download | cherrypy-git-dc574c422886d192b33a48b036d0e9839c3cc6e0.tar.gz |
Convert all strings to conform single-quoted style
pre-commit run double-quote-string-fixer --all-files
Diffstat (limited to 'cherrypy')
101 files changed, 2760 insertions, 2760 deletions
diff --git a/cherrypy/__init__.py b/cherrypy/__init__.py index b309c942..8c3f0dac 100644 --- a/cherrypy/__init__.py +++ b/cherrypy/__init__.py @@ -147,9 +147,9 @@ class _HandleSignalsPlugin(object): def subscribe(self): """Add the handlers based on the platform""" - if hasattr(self.bus, "signal_handler"): + if hasattr(self.bus, 'signal_handler'): self.bus.signal_handler.subscribe() - if hasattr(self.bus, "console_control_handler"): + if hasattr(self.bus, 'console_control_handler'): self.bus.console_control_handler.subscribe() engine.signals = _HandleSignalsPlugin(engine) @@ -159,7 +159,7 @@ server = _cpserver.Server() server.subscribe() -def quickstart(root=None, script_name="", config=None): +def quickstart(root=None, script_name='', config=None): """Mount the given root, start the builtin server (and engine), then block. root: an instance of a "controller class" (a collection of page handler @@ -198,8 +198,8 @@ class _Serving(_local): thread-safe way. """ - request = _cprequest.Request(_httputil.Host("127.0.0.1", 80), - _httputil.Host("127.0.0.1", 1111)) + request = _cprequest.Request(_httputil.Host('127.0.0.1', 80), + _httputil.Host('127.0.0.1', 1111)) """ The request object for the current thread. In the main thread, and any threads which are not receiving HTTP requests, this is None.""" @@ -232,7 +232,7 @@ class _ThreadLocalProxy(object): return getattr(child, name) def __setattr__(self, name, value): - if name in ("__attrname__", ): + if name in ('__attrname__', ): object.__setattr__(self, name, value) else: child = getattr(serving, self.__attrname__) @@ -364,8 +364,8 @@ config.defaults = { 'tools.trailing_slash.on': True, 'tools.encode.on': True } -config.namespaces["log"] = lambda k, v: setattr(log, k, v) -config.namespaces["checker"] = lambda k, v: setattr(checker, k, v) +config.namespaces['log'] = lambda k, v: setattr(log, k, v) +config.namespaces['checker'] = lambda k, v: setattr(checker, k, v) # Must reset to get our defaults applied. config.reset() diff --git a/cherrypy/_cpchecker.py b/cherrypy/_cpchecker.py index 4ef82597..d67f9ada 100644 --- a/cherrypy/_cpchecker.py +++ b/cherrypy/_cpchecker.py @@ -33,7 +33,7 @@ class Checker(object): warnings.formatwarning = self.formatwarning try: for name in dir(self): - if name.startswith("check_"): + if name.startswith('check_'): method = getattr(self, name) if method and hasattr(method, '__call__'): method() @@ -42,7 +42,7 @@ class Checker(object): def formatwarning(self, message, category, filename, lineno, line=None): """Function to format a warning.""" - return "CherryPy Checker:\n%s\n\n" % message + return 'CherryPy Checker:\n%s\n\n' % message # This value should be set inside _cpconfig. global_config_contained_paths = False @@ -57,13 +57,13 @@ class Checker(object): continue if sn == '': continue - sn_atoms = sn.strip("/").split("/") + sn_atoms = sn.strip('/').split('/') for key in app.config.keys(): - key_atoms = key.strip("/").split("/") + key_atoms = key.strip('/').split('/') if key_atoms[:len(sn_atoms)] == sn_atoms: warnings.warn( - "The application mounted at %r has config " - "entries that start with its script name: %r" % (sn, + 'The application mounted at %r has config ' + 'entries that start with its script name: %r' % (sn, key)) def check_site_config_entries_in_app_config(self): @@ -76,17 +76,17 @@ class Checker(object): for section, entries in iteritems(app.config): if section.startswith('/'): for key, value in iteritems(entries): - for n in ("engine.", "server.", "tree.", "checker."): + for n in ('engine.', 'server.', 'tree.', 'checker.'): if key.startswith(n): - msg.append("[%s] %s = %s" % + msg.append('[%s] %s = %s' % (section, key, value)) if msg: msg.insert(0, - "The application mounted at %r contains the " - "following config entries, which are only allowed " - "in site-wide config. Move them to a [global] " - "section and pass them to cherrypy.config.update() " - "instead of tree.mount()." % sn) + 'The application mounted at %r contains the ' + 'following config entries, which are only allowed ' + 'in site-wide config. Move them to a [global] ' + 'section and pass them to cherrypy.config.update() ' + 'instead of tree.mount().' % sn) warnings.warn(os.linesep.join(msg)) def check_skipped_app_config(self): @@ -95,13 +95,13 @@ class Checker(object): if not isinstance(app, cherrypy.Application): continue if not app.config: - msg = "The Application mounted at %r has an empty config." % sn + msg = 'The Application mounted at %r has an empty config.' % sn if self.global_config_contained_paths: - msg += (" It looks like the config you passed to " - "cherrypy.config.update() contains application-" - "specific sections. You must explicitly pass " - "application config via " - "cherrypy.tree.mount(..., config=app_config)") + msg += (' It looks like the config you passed to ' + 'cherrypy.config.update() contains application-' + 'specific sections. You must explicitly pass ' + 'application config via ' + 'cherrypy.tree.mount(..., config=app_config)') warnings.warn(msg) return @@ -115,12 +115,12 @@ class Checker(object): if not app.config: continue for key in app.config.keys(): - if key.startswith("[") or key.endswith("]"): + if key.startswith('[') or key.endswith(']'): warnings.warn( - "The application mounted at %r has config " - "section names with extraneous brackets: %r. " - "Config *files* need brackets; config *dicts* " - "(e.g. passed to tree.mount) do not." % (sn, key)) + 'The application mounted at %r has config ' + 'section names with extraneous brackets: %r. ' + 'Config *files* need brackets; config *dicts* ' + '(e.g. passed to tree.mount) do not.' % (sn, key)) def check_static_paths(self): """Check Application config for incorrect static paths.""" @@ -132,47 +132,47 @@ class Checker(object): request.app = app for section in app.config: # get_resource will populate request.config - request.get_resource(section + "/dummy.html") + request.get_resource(section + '/dummy.html') conf = request.config.get - if conf("tools.staticdir.on", False): - msg = "" - root = conf("tools.staticdir.root") - dir = conf("tools.staticdir.dir") + if conf('tools.staticdir.on', False): + msg = '' + root = conf('tools.staticdir.root') + dir = conf('tools.staticdir.dir') if dir is None: - msg = "tools.staticdir.dir is not set." + msg = 'tools.staticdir.dir is not set.' else: - fulldir = "" + fulldir = '' if os.path.isabs(dir): fulldir = dir if root: - msg = ("dir is an absolute path, even " - "though a root is provided.") + msg = ('dir is an absolute path, even ' + 'though a root is provided.') testdir = os.path.join(root, dir[1:]) if os.path.exists(testdir): msg += ( - "\nIf you meant to serve the " - "filesystem folder at %r, remove the " - "leading slash from dir." % (testdir,)) + '\nIf you meant to serve the ' + 'filesystem folder at %r, remove the ' + 'leading slash from dir.' % (testdir,)) else: if not root: msg = ( - "dir is a relative path and " - "no root provided.") + 'dir is a relative path and ' + 'no root provided.') else: fulldir = os.path.join(root, dir) if not os.path.isabs(fulldir): - msg = ("%r is not an absolute path." % ( + msg = ('%r is not an absolute path.' % ( fulldir,)) if fulldir and not os.path.exists(fulldir): if msg: - msg += "\n" - msg += ("%r (root + dir) is not an existing " - "filesystem path." % fulldir) + msg += '\n' + msg += ('%r (root + dir) is not an existing ' + 'filesystem path.' % fulldir) if msg: - warnings.warn("%s\nsection: [%s]\nroot: %r\ndir: %r" + warnings.warn('%s\nsection: [%s]\nroot: %r\ndir: %r' % (msg, section, root, dir)) # -------------------------- Compatibility -------------------------- # @@ -198,19 +198,19 @@ class Checker(object): if isinstance(conf, dict): for k, v in conf.items(): if k in self.obsolete: - warnings.warn("%r is obsolete. Use %r instead.\n" - "section: [%s]" % + warnings.warn('%r is obsolete. Use %r instead.\n' + 'section: [%s]' % (k, self.obsolete[k], section)) elif k in self.deprecated: - warnings.warn("%r is deprecated. Use %r instead.\n" - "section: [%s]" % + warnings.warn('%r is deprecated. Use %r instead.\n' + 'section: [%s]' % (k, self.deprecated[k], section)) else: if section in self.obsolete: - warnings.warn("%r is obsolete. Use %r instead." + warnings.warn('%r is obsolete. Use %r instead.' % (section, self.obsolete[section])) elif section in self.deprecated: - warnings.warn("%r is deprecated. Use %r instead." + warnings.warn('%r is deprecated. Use %r instead.' % (section, self.deprecated[section])) def check_compatibility(self): @@ -225,7 +225,7 @@ class Checker(object): extra_config_namespaces = [] def _known_ns(self, app): - ns = ["wsgi"] + ns = ['wsgi'] ns.extend(copykeys(app.toolboxes)) ns.extend(copykeys(app.namespaces)) ns.extend(copykeys(app.request_class.namespaces)) @@ -233,32 +233,32 @@ class Checker(object): ns += self.extra_config_namespaces for section, conf in app.config.items(): - is_path_section = section.startswith("/") + is_path_section = section.startswith('/') if is_path_section and isinstance(conf, dict): for k, v in conf.items(): - atoms = k.split(".") + atoms = k.split('.') if len(atoms) > 1: if atoms[0] not in ns: # Spit out a special warning if a known # namespace is preceded by "cherrypy." - if atoms[0] == "cherrypy" and atoms[1] in ns: + if atoms[0] == 'cherrypy' and atoms[1] in ns: msg = ( - "The config entry %r is invalid; " - "try %r instead.\nsection: [%s]" - % (k, ".".join(atoms[1:]), section)) + 'The config entry %r is invalid; ' + 'try %r instead.\nsection: [%s]' + % (k, '.'.join(atoms[1:]), section)) else: msg = ( - "The config entry %r is invalid, " - "because the %r config namespace " - "is unknown.\n" - "section: [%s]" % (k, atoms[0], section)) + 'The config entry %r is invalid, ' + 'because the %r config namespace ' + 'is unknown.\n' + 'section: [%s]' % (k, atoms[0], section)) warnings.warn(msg) - elif atoms[0] == "tools": + elif atoms[0] == 'tools': if atoms[1] not in dir(cherrypy.tools): msg = ( - "The config entry %r may be invalid, " - "because the %r tool was not found.\n" - "section: [%s]" % (k, atoms[1], section)) + 'The config entry %r may be invalid, ' + 'because the %r tool was not found.\n' + 'section: [%s]' % (k, atoms[1], section)) warnings.warn(msg) def check_config_namespaces(self): @@ -282,17 +282,17 @@ class Checker(object): continue vtype = type(getattr(obj, name, None)) if vtype in b: - self.known_config_types[namespace + "." + name] = vtype + self.known_config_types[namespace + '.' + name] = vtype - traverse(cherrypy.request, "request") - traverse(cherrypy.response, "response") - traverse(cherrypy.server, "server") - traverse(cherrypy.engine, "engine") - traverse(cherrypy.log, "log") + traverse(cherrypy.request, 'request') + traverse(cherrypy.response, 'response') + traverse(cherrypy.server, 'server') + traverse(cherrypy.engine, 'engine') + traverse(cherrypy.log, 'log') def _known_types(self, config): - msg = ("The config entry %r in section %r is of type %r, " - "which does not match the expected type %r.") + msg = ('The config entry %r in section %r is of type %r, ' + 'which does not match the expected type %r.') for section, conf in config.items(): if isinstance(conf, dict): @@ -326,7 +326,7 @@ class Checker(object): for k, v in cherrypy.config.items(): if k == 'server.socket_host' and v == 'localhost': warnings.warn("The use of 'localhost' as a socket host can " - "cause problems on newer systems, since " + 'cause problems on newer systems, since ' "'localhost' can map to either an IPv4 or an " "IPv6 address. You should use '127.0.0.1' " "or '[::1]' instead.") diff --git a/cherrypy/_cpcompat.py b/cherrypy/_cpcompat.py index 9d4e4c37..9430dbbf 100644 --- a/cherrypy/_cpcompat.py +++ b/cherrypy/_cpcompat.py @@ -88,7 +88,7 @@ else: def assert_native(n): if not isinstance(n, str): - raise TypeError("n must be a native str (got %s)" % type(n).__name__) + raise TypeError('n must be a native str (got %s)' % type(n).__name__) try: # Python 3.1+ diff --git a/cherrypy/_cpcompat_subprocess.py b/cherrypy/_cpcompat_subprocess.py index b0856645..e69a0eae 100644 --- a/cherrypy/_cpcompat_subprocess.py +++ b/cherrypy/_cpcompat_subprocess.py @@ -399,7 +399,7 @@ import signal import sys -mswindows = (sys.platform == "win32") +mswindows = (sys.platform == 'win32') # Exception classes used by this module. @@ -449,8 +449,8 @@ else: _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) -__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", - "check_output", "CalledProcessError"] +__all__ = ['Popen', 'PIPE', 'STDOUT', 'call', 'check_call', + 'check_output', 'CalledProcessError'] if mswindows: from _subprocess import ( # noqa @@ -460,12 +460,12 @@ if mswindows: STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW ) - __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP", - "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE", - "STD_ERROR_HANDLE", "SW_HIDE", - "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"]) + __all__.extend(['CREATE_NEW_CONSOLE', 'CREATE_NEW_PROCESS_GROUP', + 'STD_INPUT_HANDLE', 'STD_OUTPUT_HANDLE', + 'STD_ERROR_HANDLE', 'SW_HIDE', + 'STARTF_USESTDHANDLES', 'STARTF_USESHOWWINDOW']) try: - MAXFD = os.sysconf("SC_OPEN_MAX") + MAXFD = os.sysconf('SC_OPEN_MAX') except: MAXFD = 256 @@ -520,7 +520,7 @@ def check_call(*popenargs, **kwargs): """ retcode = call(*popenargs, **kwargs) if retcode: - cmd = kwargs.get("args") + cmd = kwargs.get('args') if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) @@ -553,7 +553,7 @@ def check_output(*popenargs, **kwargs): output, unused_err = process.communicate() retcode = process.poll() if retcode: - cmd = kwargs.get("args") + cmd = kwargs.get('args') if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) @@ -599,7 +599,7 @@ def list2cmdline(seq): if result: result.append(' ') - needquote = (" " in arg) or ("\t" in arg) or not arg + needquote = (' ' in arg) or ('\t' in arg) or not arg if needquote: result.append('"') @@ -642,25 +642,25 @@ class Popen(object): self._child_created = False if not isinstance(bufsize, (int, long)): - raise TypeError("bufsize must be an integer") + raise TypeError('bufsize must be an integer') if mswindows: if preexec_fn is not None: - raise ValueError("preexec_fn is not supported on Windows " - "platforms") + raise ValueError('preexec_fn is not supported on Windows ' + 'platforms') if close_fds and (stdin is not None or stdout is not None or stderr is not None): - raise ValueError("close_fds is not supported on Windows " - "platforms if you redirect " - "stdin/stdout/stderr") + raise ValueError('close_fds is not supported on Windows ' + 'platforms if you redirect ' + 'stdin/stdout/stderr') else: # POSIX if startupinfo is not None: - raise ValueError("startupinfo is only supported on Windows " - "platforms") + raise ValueError('startupinfo is only supported on Windows ' + 'platforms') if creationflags != 0: - raise ValueError("creationflags is only supported on Windows " - "platforms") + raise ValueError('creationflags is only supported on Windows ' + 'platforms') self.stdin = None self.stdout = None @@ -717,8 +717,8 @@ class Popen(object): self.stderr = os.fdopen(errread, 'rb', bufsize) def _translate_newlines(self, data): - data = data.replace("\r\n", "\n") - data = data.replace("\r", "\n") + data = data.replace('\r\n', '\n') + data = data.replace('\r', '\n') return data def __del__(self, _maxint=sys.maxint, _active=_active): @@ -848,16 +848,16 @@ class Popen(object): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join( os.path.dirname(_subprocess.GetModuleFileName(0)), - "w9xpopen.exe") + 'w9xpopen.exe') if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), - "w9xpopen.exe") + 'w9xpopen.exe') if not os.path.exists(w9xpopen): - raise RuntimeError("Cannot locate w9xpopen.exe, which is " - "needed for Popen to work with your " - "shell or platform.") + raise RuntimeError('Cannot locate w9xpopen.exe, which is ' + 'needed for Popen to work with your ' + 'shell or platform.') return w9xpopen def _execute_child(self, args, executable, preexec_fn, close_fds, @@ -883,10 +883,10 @@ class Popen(object): if shell: startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = _subprocess.SW_HIDE - comspec = os.environ.get("COMSPEC", "cmd.exe") + comspec = os.environ.get('COMSPEC', 'cmd.exe') args = '{0} /c "{1}"'.format(comspec, args) if (_subprocess.GetVersion() >= 0x80000000 or - os.path.basename(comspec).lower() == "command.com"): + os.path.basename(comspec).lower() == 'command.com'): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more # information, see KB Q150956 @@ -1030,7 +1030,7 @@ class Popen(object): elif sig == signal.CTRL_BREAK_EVENT: os.kill(self.pid, signal.CTRL_BREAK_EVENT) else: - raise ValueError("Unsupported signal: {0}".format(sig)) + raise ValueError('Unsupported signal: {0}'.format(sig)) def terminate(self): """Terminates the process @@ -1138,7 +1138,7 @@ class Popen(object): args = list(args) if shell: - args = ["/bin/sh", "-c"] + args + args = ['/bin/sh', '-c'] + args if executable: args[0] = executable @@ -1254,7 +1254,7 @@ class Popen(object): # be sure the FD is closed no matter what os.close(errpipe_read) - if data != "": + if data != '': try: _eintr_retry_call(os.waitpid, self.pid, 0) except OSError as e: @@ -1277,7 +1277,7 @@ class Popen(object): self.returncode = _WEXITSTATUS(sts) else: # Should never happen - raise RuntimeError("Unknown child exit status!") + raise RuntimeError('Unknown child exit status!') def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, _WNOHANG=os.WNOHANG, _os_error=os.error): @@ -1450,14 +1450,14 @@ class Popen(object): if self.stdout in rlist: data = os.read(self.stdout.fileno(), 1024) - if data == "": + if data == '': self.stdout.close() read_set.remove(self.stdout) stdout.append(data) if self.stderr in rlist: data = os.read(self.stderr.fileno(), 1024) - if data == "": + if data == '': self.stderr.close() read_set.remove(self.stderr) stderr.append(data) @@ -1484,41 +1484,41 @@ def _demo_posix(): # # Example 1: Simple redirection: Get process list # - plist = Popen(["ps"], stdout=PIPE).communicate()[0] - print("Process list:") + plist = Popen(['ps'], stdout=PIPE).communicate()[0] + print('Process list:') print(plist) # # Example 2: Change uid before executing child # if os.getuid() == 0: - p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) + p = Popen(['id'], preexec_fn=lambda: os.setuid(100)) p.wait() # # Example 3: Connecting several subprocesses # print("Looking for 'hda'...") - p1 = Popen(["dmesg"], stdout=PIPE) - p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) + p1 = Popen(['dmesg'], stdout=PIPE) + p2 = Popen(['grep', 'hda'], stdin=p1.stdout, stdout=PIPE) print(repr(p2.communicate()[0])) # # Example 4: Catch execution error # print() - print("Trying a weird file...") + print('Trying a weird file...') try: - print(Popen(["/this/path/does/not/exist"]).communicate()) + print(Popen(['/this/path/does/not/exist']).communicate()) except OSError as e: if e.errno == errno.ENOENT: print("The file didn't exist. I thought so...") - print("Child traceback:") + print('Child traceback:') print(e.child_traceback) else: - print("Error", e.errno) + print('Error', e.errno) else: - print("Gosh. No error.", e, file=sys.stderr) + print('Gosh. No error.', e, file=sys.stderr) def _demo_windows(): @@ -1526,19 +1526,19 @@ def _demo_windows(): # Example 1: Connecting several subprocesses # print("Looking for 'PROMPT' in set output...") - p1 = Popen("set", stdout=PIPE, shell=True) + p1 = Popen('set', stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) print(repr(p2.communicate()[0])) # # Example 2: Simple execution of program # - print("Executing calc...") - p = Popen("calc") + print('Executing calc...') + p = Popen('calc') p.wait() -if __name__ == "__main__": +if __name__ == '__main__': if mswindows: _demo_windows() else: diff --git a/cherrypy/_cpconfig.py b/cherrypy/_cpconfig.py index 7afb9131..674199f4 100644 --- a/cherrypy/_cpconfig.py +++ b/cherrypy/_cpconfig.py @@ -139,9 +139,9 @@ def merge(base, other): for section, value_map in reprconf.as_dict(other).items(): if not isinstance(value_map, dict): raise ValueError( - "Application config must include section headers, but the " + 'Application config must include section headers, but the ' "config you tried to merge doesn't have any sections. " - "Wrap your config in another dict with paths as section " + 'Wrap your config in another dict with paths as section ' "headers, for example: {'/': config}.") base.setdefault(section, {}).update(value_map) @@ -159,12 +159,12 @@ class Config(reprconf.Config): def _apply(self, config): """Update self from a dict.""" - if isinstance(config.get("global"), dict): + if isinstance(config.get('global'), dict): if len(config) > 1: cherrypy.checker.global_config_contained_paths = True - config = config["global"] + config = config['global'] if 'tools.staticdir.dir' in config: - config['tools.staticdir.section'] = "global" + config['tools.staticdir.section'] = 'global' reprconf.Config._apply(self, config) @staticmethod @@ -172,8 +172,8 @@ class Config(reprconf.Config): """Decorator for page handlers to set _cp_config.""" if args: raise TypeError( - "The cherrypy.config decorator does not accept positional " - "arguments; you must use keyword arguments.") + 'The cherrypy.config decorator does not accept positional ' + 'arguments; you must use keyword arguments.') def tool_decorator(f): _Vars(f).setdefault('_cp_config', {}).update(kwargs) @@ -197,14 +197,14 @@ class _Vars(object): # Sphinx begin config.environments Config.environments = environments = { - "staging": { + 'staging': { 'engine.autoreload.on': False, 'checker.on': False, 'tools.log_headers.on': False, 'request.show_tracebacks': False, 'request.show_mismatched_params': False, }, - "production": { + 'production': { 'engine.autoreload.on': False, 'checker.on': False, 'tools.log_headers.on': False, @@ -212,7 +212,7 @@ Config.environments = environments = { 'request.show_mismatched_params': False, 'log.screen': False, }, - "embedded": { + 'embedded': { # For use with CherryPy embedded in another deployment stack. 'engine.autoreload.on': False, 'checker.on': False, @@ -223,7 +223,7 @@ Config.environments = environments = { 'engine.SIGHUP': None, 'engine.SIGTERM': None, }, - "test_suite": { + 'test_suite': { 'engine.autoreload.on': False, 'checker.on': False, 'tools.log_headers.on': False, @@ -237,11 +237,11 @@ Config.environments = environments = { def _server_namespace_handler(k, v): """Config handler for the "server" namespace.""" - atoms = k.split(".", 1) + atoms = k.split('.', 1) if len(atoms) > 1: # Special-case config keys of the form 'server.servername.socket_port' # to configure additional HTTP servers. - if not hasattr(cherrypy, "servers"): + if not hasattr(cherrypy, 'servers'): cherrypy.servers = {} servername, k = atoms @@ -260,7 +260,7 @@ def _server_namespace_handler(k, v): setattr(cherrypy.servers[servername], k, v) else: setattr(cherrypy.server, k, v) -Config.namespaces["server"] = _server_namespace_handler +Config.namespaces['server'] = _server_namespace_handler def _engine_namespace_handler(k, v): @@ -271,8 +271,8 @@ def _engine_namespace_handler(k, v): engine.subscribe('SIGHUP', v) elif k == 'SIGTERM': engine.subscribe('SIGTERM', v) - elif "." in k: - plugin, attrname = k.split(".", 1) + elif '.' in k: + plugin, attrname = k.split('.', 1) plugin = getattr(engine, plugin) if attrname == 'on': if v and hasattr(getattr(plugin, 'subscribe', None), '__call__'): @@ -287,7 +287,7 @@ def _engine_namespace_handler(k, v): setattr(plugin, attrname, v) else: setattr(engine, k, v) -Config.namespaces["engine"] = _engine_namespace_handler +Config.namespaces['engine'] = _engine_namespace_handler def _tree_namespace_handler(k, v): @@ -295,9 +295,9 @@ def _tree_namespace_handler(k, v): if isinstance(v, dict): for script_name, app in v.items(): cherrypy.tree.graft(app, script_name) - msg = "Mounted: %s on %s" % (app, script_name or "/") + msg = 'Mounted: %s on %s' % (app, script_name or '/') cherrypy.engine.log(msg) else: cherrypy.tree.graft(v, v.script_name) - cherrypy.engine.log("Mounted: %s on %s" % (v, v.script_name or "/")) -Config.namespaces["tree"] = _tree_namespace_handler + cherrypy.engine.log('Mounted: %s on %s' % (v, v.script_name or '/')) +Config.namespaces['tree'] = _tree_namespace_handler diff --git a/cherrypy/_cpdispatch.py b/cherrypy/_cpdispatch.py index 2cb03c7e..eb5484c7 100644 --- a/cherrypy/_cpdispatch.py +++ b/cherrypy/_cpdispatch.py @@ -39,7 +39,7 @@ class PageHandler(object): args = property( get_args, set_args, - doc="The ordered args should be accessible from post dispatch hooks" + doc='The ordered args should be accessible from post dispatch hooks' ) def get_kwargs(self): @@ -52,7 +52,7 @@ class PageHandler(object): kwargs = property( get_kwargs, set_kwargs, - doc="The named kwargs should be accessible from post dispatch hooks" + doc='The named kwargs should be accessible from post dispatch hooks' ) def __call__(self): @@ -153,7 +153,7 @@ def test_callable_spec(callable, callable_args, callable_kwargs): # arguments it's definitely a 404. message = None if show_mismatched_params: - message = "Missing parameters: %s" % ",".join(missing_args) + message = 'Missing parameters: %s' % ','.join(missing_args) raise cherrypy.HTTPError(404, message=message) # the extra positional arguments come from the path - 404 Not Found @@ -175,8 +175,8 @@ def test_callable_spec(callable, callable_args, callable_kwargs): message = None if show_mismatched_params: - message = "Multiple values for parameters: "\ - "%s" % ",".join(multiple_args) + message = 'Multiple values for parameters: '\ + '%s' % ','.join(multiple_args) raise cherrypy.HTTPError(error, message=message) if not varkw and varkw_usage > 0: @@ -186,8 +186,8 @@ def test_callable_spec(callable, callable_args, callable_kwargs): if extra_qs_params: message = None if show_mismatched_params: - message = "Unexpected query string "\ - "parameters: %s" % ", ".join(extra_qs_params) + message = 'Unexpected query string '\ + 'parameters: %s' % ', '.join(extra_qs_params) raise cherrypy.HTTPError(404, message=message) # If there were any extra body parameters, it's a 400 Not Found @@ -195,8 +195,8 @@ def test_callable_spec(callable, callable_args, callable_kwargs): if extra_body_params: message = None if show_mismatched_params: - message = "Unexpected body parameters: "\ - "%s" % ", ".join(extra_body_params) + message = 'Unexpected body parameters: '\ + '%s' % ', '.join(extra_body_params) raise cherrypy.HTTPError(400, message=message) @@ -244,14 +244,14 @@ if sys.version_info < (3, 0): def validate_translator(t): if not isinstance(t, str) or len(t) != 256: raise ValueError( - "The translate argument must be a str of len 256.") + 'The translate argument must be a str of len 256.') else: punctuation_to_underscores = str.maketrans( string.punctuation, '_' * len(string.punctuation)) def validate_translator(t): if not isinstance(t, dict): - raise ValueError("The translate argument must be a dict.") + raise ValueError('The translate argument must be a dict.') class Dispatcher(object): @@ -289,7 +289,7 @@ class Dispatcher(object): if func: # Decode any leftover %2F in the virtual_path atoms. - vpath = [x.replace("%2F", "/") for x in vpath] + vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.NotFound() @@ -323,10 +323,10 @@ class Dispatcher(object): fullpath_len = len(fullpath) segleft = fullpath_len nodeconf = {} - if hasattr(root, "_cp_config"): + if hasattr(root, '_cp_config'): nodeconf.update(root._cp_config) - if "/" in app.config: - nodeconf.update(app.config["/"]) + if '/' in app.config: + nodeconf.update(app.config['/']) object_trail = [['root', root, nodeconf, segleft]] node = root @@ -361,9 +361,9 @@ class Dispatcher(object): if segleft > pre_len: # No path segment was removed. Raise an error. raise cherrypy.CherryPyException( - "A vpath segment was added. Custom dispatchers may only " - + "remove elements. While trying to process " - + "{0} in {1}".format(name, fullpath) + 'A vpath segment was added. Custom dispatchers may only ' + + 'remove elements. While trying to process ' + + '{0} in {1}'.format(name, fullpath) ) elif segleft == pre_len: # Assume that the handler used the current path segment, but @@ -375,7 +375,7 @@ class Dispatcher(object): if node is not None: # Get _cp_config attached to this node. - if hasattr(node, "_cp_config"): + if hasattr(node, '_cp_config'): nodeconf.update(node._cp_config) # Mix in values from app.config for this path. @@ -414,16 +414,16 @@ class Dispatcher(object): continue # Try a "default" method on the current leaf. - if hasattr(candidate, "default"): + if hasattr(candidate, 'default'): defhandler = candidate.default if getattr(defhandler, 'exposed', False): # Insert any extra _cp_config from the default handler. - conf = getattr(defhandler, "_cp_config", {}) + conf = getattr(defhandler, '_cp_config', {}) object_trail.insert( - i + 1, ["default", defhandler, conf, segleft]) + i + 1, ['default', defhandler, conf, segleft]) request.config = set_conf() # See https://github.com/cherrypy/cherrypy/issues/613 - request.is_index = path.endswith("/") + request.is_index = path.endswith('/') return defhandler, fullpath[fullpath_len - segleft:-1] # Uncomment the next line to restrict positional params to @@ -470,23 +470,23 @@ class MethodDispatcher(Dispatcher): if resource: # Set Allow header avail = [m for m in dir(resource) if m.isupper()] - if "GET" in avail and "HEAD" not in avail: - avail.append("HEAD") + if 'GET' in avail and 'HEAD' not in avail: + avail.append('HEAD') avail.sort() - cherrypy.serving.response.headers['Allow'] = ", ".join(avail) + cherrypy.serving.response.headers['Allow'] = ', '.join(avail) # Find the subhandler meth = request.method.upper() func = getattr(resource, meth, None) - if func is None and meth == "HEAD": - func = getattr(resource, "GET", None) + if func is None and meth == 'HEAD': + func = getattr(resource, 'GET', None) if func: # Grab any _cp_config on the subhandler. - if hasattr(func, "_cp_config"): + if hasattr(func, '_cp_config'): request.config.update(func._cp_config) # Decode any leftover %2F in the virtual_path atoms. - vpath = [x.replace("%2F", "/") for x in vpath] + vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.HTTPError(405) @@ -554,28 +554,28 @@ class RoutesDispatcher(object): # Get config for the root object/path. request.config = base = cherrypy.config.copy() - curpath = "" + curpath = '' def merge(nodeconf): if 'tools.staticdir.dir' in nodeconf: - nodeconf['tools.staticdir.section'] = curpath or "/" + nodeconf['tools.staticdir.section'] = curpath or '/' base.update(nodeconf) app = request.app root = app.root - if hasattr(root, "_cp_config"): + if hasattr(root, '_cp_config'): merge(root._cp_config) - if "/" in app.config: - merge(app.config["/"]) + if '/' in app.config: + merge(app.config['/']) # Mix in values from app.config. - atoms = [x for x in path_info.split("/") if x] + atoms = [x for x in path_info.split('/') if x] if atoms: last = atoms.pop() else: last = None for atom in atoms: - curpath = "/".join((curpath, atom)) + curpath = '/'.join((curpath, atom)) if curpath in app.config: merge(app.config[curpath]) @@ -587,14 +587,14 @@ class RoutesDispatcher(object): if isinstance(controller, classtype): controller = controller() # Get config from the controller. - if hasattr(controller, "_cp_config"): + if hasattr(controller, '_cp_config'): merge(controller._cp_config) action = result.get('action') if action is not None: handler = getattr(controller, action, None) # Get config from the handler - if hasattr(handler, "_cp_config"): + if hasattr(handler, '_cp_config'): merge(handler._cp_config) else: handler = controller @@ -602,7 +602,7 @@ class RoutesDispatcher(object): # Do the last path atom here so it can # override the controller's _cp_config. if last: - curpath = "/".join((curpath, last)) + curpath = '/'.join((curpath, last)) if curpath in app.config: merge(app.config[curpath]) @@ -666,9 +666,9 @@ def VirtualHost(next_dispatcher=Dispatcher(), use_x_forwarded_host=True, domain = header('Host', '') if use_x_forwarded_host: - domain = header("X-Forwarded-Host", domain) + domain = header('X-Forwarded-Host', domain) - prefix = domains.get(domain, "") + prefix = domains.get(domain, '') if prefix: path_info = httputil.urljoin(prefix, path_info) diff --git a/cherrypy/_cperror.py b/cherrypy/_cperror.py index ee7fad69..205aa33b 100644 --- a/cherrypy/_cperror.py +++ b/cherrypy/_cperror.py @@ -150,14 +150,14 @@ class InternalRedirect(CherryPyException): URL. """ - def __init__(self, path, query_string=""): + def __init__(self, path, query_string=''): import cherrypy self.request = cherrypy.serving.request self.query_string = query_string - if "?" in path: + if '?' in path: # Separate any params included in the path - path, self.query_string = path.split("?", 1) + path, self.query_string = path.split('?', 1) # Note that urljoin will "do the right thing" whether url is: # 1. a URL relative to root (e.g. "/dummy") @@ -238,7 +238,7 @@ class HTTPRedirect(CherryPyException): else: status = int(status) if status < 300 or status > 399: - raise ValueError("status must be between 300 and 399.") + raise ValueError('status must be between 300 and 399.') self.status = status CherryPyException.__init__(self, abs_urls, status) @@ -255,7 +255,7 @@ class HTTPRedirect(CherryPyException): response.status = status = self.status if status in (300, 301, 302, 303, 307): - response.headers['Content-Type'] = "text/html;charset=utf-8" + response.headers['Content-Type'] = 'text/html;charset=utf-8' # "The ... URI SHOULD be given by the Location field # in the response." response.headers['Location'] = self.urls[0] @@ -264,15 +264,15 @@ class HTTPRedirect(CherryPyException): # SHOULD contain a short hypertext note with a hyperlink to the # new URI(s)." msg = { - 300: "This resource can be found at ", - 301: "This resource has permanently moved to ", - 302: "This resource resides temporarily at ", - 303: "This resource can be found at ", - 307: "This resource has moved temporarily to ", + 300: 'This resource can be found at ', + 301: 'This resource has permanently moved to ', + 302: 'This resource resides temporarily at ', + 303: 'This resource can be found at ', + 307: 'This resource has moved temporarily to ', }[status] msg += '<a href=%s>%s</a>.' msgs = [msg % (saxutils.quoteattr(u), u) for u in self.urls] - response.body = ntob("<br />\n".join(msgs), 'utf-8') + response.body = ntob('<br />\n'.join(msgs), 'utf-8') # Previous code may have set C-L, so we have to reset it # (allow finalize to set it). response.headers.pop('Content-Length', None) @@ -302,7 +302,7 @@ class HTTPRedirect(CherryPyException): # Previous code may have set C-L, so we have to reset it. response.headers.pop('Content-Length', None) else: - raise ValueError("The %s status code is unknown." % status) + raise ValueError('The %s status code is unknown.' % status) def __call__(self): """Use this exception as a request.handler (raise self).""" @@ -318,9 +318,9 @@ def clean_headers(status): # Remove headers which applied to the original content, # but do not apply to the error page. respheaders = response.headers - for key in ["Accept-Ranges", "Age", "ETag", "Location", "Retry-After", - "Vary", "Content-Encoding", "Content-Length", "Expires", - "Content-Location", "Content-MD5", "Last-Modified"]: + for key in ['Accept-Ranges', 'Age', 'ETag', 'Location', 'Retry-After', + 'Vary', 'Content-Encoding', 'Content-Length', 'Expires', + 'Content-Location', 'Content-MD5', 'Last-Modified']: if key in respheaders: del respheaders[key] @@ -331,8 +331,8 @@ def clean_headers(status): # specifies the current length of the selected resource. # A response with status code 206 (Partial Content) MUST NOT # include a Content-Range field with a byte-range- resp-spec of "*". - if "Content-Range" in respheaders: - del respheaders["Content-Range"] + if 'Content-Range' in respheaders: + del respheaders['Content-Range'] class HTTPError(CherryPyException): @@ -372,7 +372,7 @@ class HTTPError(CherryPyException): raise self.__class__(500, _exc_info()[1].args[0]) if self.code < 400 or self.code > 599: - raise ValueError("status must be between 400 and 599.") + raise ValueError('status must be between 400 and 599.') # See http://www.python.org/dev/peps/pep-0352/ # self.message = message @@ -490,7 +490,7 @@ def get_error_page(status, **kwargs): # We can't use setdefault here, because some # callers send None for kwarg values. if kwargs.get('status') is None: - kwargs['status'] = "%s %s" % (code, reason) + kwargs['status'] = '%s %s' % (code, reason) if kwargs.get('message') is None: kwargs['message'] = message if kwargs.get('traceback') is None: @@ -500,7 +500,7 @@ def get_error_page(status, **kwargs): for k, v in iteritems(kwargs): if v is None: - kwargs[k] = "" + kwargs[k] = '' else: kwargs[k] = _escape(kwargs[k]) @@ -538,12 +538,12 @@ def get_error_page(status, **kwargs): e = _format_exception(*_exc_info())[-1] m = kwargs['message'] if m: - m += "<br />" - m += "In addition, the custom error page failed:\n<br />%s" % e + m += '<br />' + m += 'In addition, the custom error page failed:\n<br />%s' % e kwargs['message'] = m response = cherrypy.serving.response - response.headers['Content-Type'] = "text/html;charset=utf-8" + response.headers['Content-Type'] = 'text/html;charset=utf-8' result = template % kwargs return result.encode('utf-8') @@ -575,7 +575,7 @@ def _be_ie_unfriendly(status): if l and l < s: # IN ADDITION: the response must be written to IE # in one chunk or it will still get replaced! Bah. - content = content + (ntob(" ") * (s - l)) + content = content + (ntob(' ') * (s - l)) response.body = content response.headers['Content-Length'] = str(len(content)) @@ -586,9 +586,9 @@ def format_exc(exc=None): if exc is None: exc = _exc_info() if exc == (None, None, None): - return "" + return '' import traceback - return "".join(traceback.format_exception(*exc)) + return ''.join(traceback.format_exception(*exc)) finally: del exc @@ -610,13 +610,13 @@ def bare_error(extrabody=None): # it cannot be allowed to fail. Therefore, don't add to it! # In particular, don't call any other CP functions. - body = ntob("Unrecoverable error in the server.") + body = ntob('Unrecoverable error in the server.') if extrabody is not None: if not isinstance(extrabody, bytes): extrabody = extrabody.encode('utf-8') - body += ntob("\n") + extrabody + body += ntob('\n') + extrabody - return (ntob("500 Internal Server Error"), + return (ntob('500 Internal Server Error'), [(ntob('Content-Type'), ntob('text/plain')), (ntob('Content-Length'), ntob(str(len(body)), 'ISO-8859-1'))], [body]) diff --git a/cherrypy/_cplogging.py b/cherrypy/_cplogging.py index 53f23430..79fe5a8d 100644 --- a/cherrypy/_cplogging.py +++ b/cherrypy/_cplogging.py @@ -121,7 +121,7 @@ from cherrypy._cpcompat import ntob # Silence the no-handlers "warning" (stderr write!) in stdlib logging logging.Logger.manager.emittedNoHandlerWarning = 1 -logfmt = logging.Formatter("%(message)s") +logfmt = logging.Formatter('%(message)s') class NullHandler(logging.Handler): @@ -172,17 +172,17 @@ class LogManager(object): cherrypy.access.<appid> """ - def __init__(self, appid=None, logger_root="cherrypy"): + def __init__(self, appid=None, logger_root='cherrypy'): self.logger_root = logger_root self.appid = appid if appid is None: - self.error_log = logging.getLogger("%s.error" % logger_root) - self.access_log = logging.getLogger("%s.access" % logger_root) + self.error_log = logging.getLogger('%s.error' % logger_root) + self.access_log = logging.getLogger('%s.access' % logger_root) else: self.error_log = logging.getLogger( - "%s.error.%s" % (logger_root, appid)) + '%s.error.%s' % (logger_root, appid)) self.access_log = logging.getLogger( - "%s.access.%s" % (logger_root, appid)) + '%s.access.%s' % (logger_root, appid)) self.error_log.setLevel(logging.INFO) self.access_log.setLevel(logging.INFO) @@ -246,19 +246,19 @@ class LogManager(object): outheaders = response.headers inheaders = request.headers if response.output_status is None: - status = "-" + status = '-' else: - status = response.output_status.split(ntob(" "), 1)[0] + status = response.output_status.split(ntob(' '), 1)[0] if six.PY3: status = status.decode('ISO-8859-1') atoms = {'h': remote.name or remote.ip, 'l': '-', - 'u': getattr(request, "login", None) or "-", + 'u': getattr(request, 'login', None) or '-', 't': self.time(), 'r': request.request_line, 's': status, - 'b': dict.get(outheaders, 'Content-Length', '') or "-", + 'b': dict.get(outheaders, 'Content-Length', '') or '-', 'f': dict.get(inheaders, 'Referer', ''), 'a': dict.get(inheaders, 'User-Agent', ''), 'o': dict.get(inheaders, 'Host', '-'), @@ -314,26 +314,26 @@ class LogManager(object): def _get_builtin_handler(self, log, key): for h in log.handlers: - if getattr(h, "_cpbuiltin", None) == key: + if getattr(h, '_cpbuiltin', None) == key: return h # ------------------------- Screen handlers ------------------------- # def _set_screen_handler(self, log, enable, stream=None): - h = self._get_builtin_handler(log, "screen") + h = self._get_builtin_handler(log, 'screen') if enable: if not h: if stream is None: stream = sys.stderr h = logging.StreamHandler(stream) h.setFormatter(logfmt) - h._cpbuiltin = "screen" + h._cpbuiltin = 'screen' log.addHandler(h) elif h: log.handlers.remove(h) def _get_screen(self): h = self._get_builtin_handler - has_h = h(self.error_log, "screen") or h(self.access_log, "screen") + has_h = h(self.error_log, 'screen') or h(self.access_log, 'screen') return bool(has_h) def _set_screen(self, newvalue): @@ -351,11 +351,11 @@ class LogManager(object): def _add_builtin_file_handler(self, log, fname): h = logging.FileHandler(fname) h.setFormatter(logfmt) - h._cpbuiltin = "file" + h._cpbuiltin = 'file' log.addHandler(h) def _set_file_handler(self, log, filename): - h = self._get_builtin_handler(log, "file") + h = self._get_builtin_handler(log, 'file') if filename: if h: if h.baseFilename != os.path.abspath(filename): @@ -370,7 +370,7 @@ class LogManager(object): log.handlers.remove(h) def _get_error_file(self): - h = self._get_builtin_handler(self.error_log, "file") + h = self._get_builtin_handler(self.error_log, 'file') if h: return h.baseFilename return '' @@ -385,7 +385,7 @@ class LogManager(object): """) def _get_access_file(self): - h = self._get_builtin_handler(self.access_log, "file") + h = self._get_builtin_handler(self.access_log, 'file') if h: return h.baseFilename return '' @@ -402,18 +402,18 @@ class LogManager(object): # ------------------------- WSGI handlers ------------------------- # def _set_wsgi_handler(self, log, enable): - h = self._get_builtin_handler(log, "wsgi") + h = self._get_builtin_handler(log, 'wsgi') if enable: if not h: h = WSGIErrorHandler() h.setFormatter(logfmt) - h._cpbuiltin = "wsgi" + h._cpbuiltin = 'wsgi' log.addHandler(h) elif h: log.handlers.remove(h) def _get_wsgi(self): - return bool(self._get_builtin_handler(self.error_log, "wsgi")) + return bool(self._get_builtin_handler(self.error_log, 'wsgi')) def _set_wsgi(self, newvalue): self._set_wsgi_handler(self.error_log, newvalue) @@ -449,16 +449,16 @@ class WSGIErrorHandler(logging.Handler): else: try: msg = self.format(record) - fs = "%s\n" + fs = '%s\n' import types # if no unicode support... - if not hasattr(types, "UnicodeType"): + if not hasattr(types, 'UnicodeType'): stream.write(fs % msg) else: try: stream.write(fs % msg) except UnicodeError: - stream.write(fs % msg.encode("UTF-8")) + stream.write(fs % msg.encode('UTF-8')) self.flush() except: self.handleError(record) diff --git a/cherrypy/_cpmodpy.py b/cherrypy/_cpmodpy.py index b5c121ed..5f0a467e 100644 --- a/cherrypy/_cpmodpy.py +++ b/cherrypy/_cpmodpy.py @@ -88,14 +88,14 @@ def setup(req): func() cherrypy.config.update({'log.screen': False, - "tools.ignore_headers.on": True, - "tools.ignore_headers.headers": ['Range'], + 'tools.ignore_headers.on': True, + 'tools.ignore_headers.headers': ['Range'], }) engine = cherrypy.engine - if hasattr(engine, "signal_handler"): + if hasattr(engine, 'signal_handler'): engine.signal_handler.unsubscribe() - if hasattr(engine, "console_control_handler"): + if hasattr(engine, 'console_control_handler'): engine.console_control_handler.unsubscribe() engine.autoreload.unsubscribe() cherrypy.server.unsubscribe() @@ -149,10 +149,10 @@ def handler(req): # Obtain a Request object from CherryPy local = req.connection.local_addr local = httputil.Host( - local[0], local[1], req.connection.local_host or "") + local[0], local[1], req.connection.local_host or '') remote = req.connection.remote_addr remote = httputil.Host( - remote[0], remote[1], req.connection.remote_host or "") + remote[0], remote[1], req.connection.remote_host or '') scheme = req.parsed_uri[0] or 'http' req.get_basic_auth_pw() @@ -165,7 +165,7 @@ def handler(req): except AttributeError: bad_value = ("You must provide a PythonOption '%s', " "either 'on' or 'off', when running a version " - "of mod_python < 3.1") + 'of mod_python < 3.1') threaded = options.get('multithread', '').lower() if threaded == 'on': @@ -173,7 +173,7 @@ def handler(req): elif threaded == 'off': threaded = False else: - raise ValueError(bad_value % "multithread") + raise ValueError(bad_value % 'multithread') forked = options.get('multiprocess', '').lower() if forked == 'on': @@ -181,16 +181,16 @@ def handler(req): elif forked == 'off': forked = False else: - raise ValueError(bad_value % "multiprocess") + raise ValueError(bad_value % 'multiprocess') - sn = cherrypy.tree.script_name(req.uri or "/") + sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: send_response(req, '404 Not Found', [], '') else: app = cherrypy.tree.apps[sn] method = req.method path = req.uri - qs = req.args or "" + qs = req.args or '' reqproto = req.protocol headers = copyitems(req.headers_in) rfile = _ReadOnlyRequest(req) @@ -200,7 +200,7 @@ def handler(req): redirections = [] while True: request, response = app.get_serving(local, remote, scheme, - "HTTP/1.1") + 'HTTP/1.1') request.login = req.user request.multithread = bool(threaded) request.multiprocess = bool(forked) @@ -219,17 +219,17 @@ def handler(req): if not recursive: if ir.path in redirections: raise RuntimeError( - "InternalRedirector visited the same URL " - "twice: %r" % ir.path) + 'InternalRedirector visited the same URL ' + 'twice: %r' % ir.path) else: # Add the *previous* path_info + qs to # redirections. if qs: - qs = "?" + qs + qs = '?' + qs redirections.append(sn + path + qs) # Munge environment and try again. - method = "GET" + method = 'GET' path = ir.path qs = ir.query_string rfile = io.BytesIO() @@ -252,7 +252,7 @@ def send_response(req, status, headers, body, stream=False): req.status = int(status[:3]) # Set response headers - req.content_type = "text/plain" + req.content_type = 'text/plain' for header, value in headers: if header.lower() == 'content-type': req.content_type = value @@ -286,13 +286,13 @@ except ImportError: return pipeout -def read_process(cmd, args=""): - fullcmd = "%s %s" % (cmd, args) +def read_process(cmd, args=''): + fullcmd = '%s %s' % (cmd, args) pipeout = popen(fullcmd) try: firstline = pipeout.readline() cmd_not_found = re.search( - ntob("(not recognized|No such file|not found)"), + ntob('(not recognized|No such file|not found)'), firstline, re.IGNORECASE ) @@ -321,8 +321,8 @@ LoadModule python_module modules/mod_python.so </Location> """ - def __init__(self, loc="/", port=80, opts=None, apache_path="apache", - handler="cherrypy._cpmodpy::handler"): + def __init__(self, loc='/', port=80, opts=None, apache_path='apache', + handler='cherrypy._cpmodpy::handler'): self.loc = loc self.port = port self.opts = opts @@ -330,25 +330,25 @@ LoadModule python_module modules/mod_python.so self.handler = handler def start(self): - opts = "".join([" PythonOption %s %s\n" % (k, v) + opts = ''.join([' PythonOption %s %s\n' % (k, v) for k, v in self.opts]) - conf_data = self.template % {"port": self.port, - "loc": self.loc, - "opts": opts, - "handler": self.handler, + conf_data = self.template % {'port': self.port, + 'loc': self.loc, + 'opts': opts, + 'handler': self.handler, } - mpconf = os.path.join(os.path.dirname(__file__), "cpmodpy.conf") + mpconf = os.path.join(os.path.dirname(__file__), 'cpmodpy.conf') f = open(mpconf, 'wb') try: f.write(conf_data) finally: f.close() - response = read_process(self.apache_path, "-k start -f %s" % mpconf) + response = read_process(self.apache_path, '-k start -f %s' % mpconf) self.ready = True return response def stop(self): - os.popen("apache -k stop") + os.popen('apache -k stop') self.ready = False diff --git a/cherrypy/_cpnative_server.py b/cherrypy/_cpnative_server.py index 8edb89c1..026b95cd 100644 --- a/cherrypy/_cpnative_server.py +++ b/cherrypy/_cpnative_server.py @@ -19,19 +19,19 @@ class NativeGateway(wsgiserver.Gateway): try: # Obtain a Request object from CherryPy local = req.server.bind_addr - local = httputil.Host(local[0], local[1], "") + local = httputil.Host(local[0], local[1], '') remote = req.conn.remote_addr, req.conn.remote_port - remote = httputil.Host(remote[0], remote[1], "") + remote = httputil.Host(remote[0], remote[1], '') scheme = req.scheme - sn = cherrypy.tree.script_name(req.uri or "/") + sn = cherrypy.tree.script_name(req.uri or '/') if sn is None: self.send_response('404 Not Found', [], ['']) else: app = cherrypy.tree.apps[sn] method = req.method path = req.path - qs = req.qs or "" + qs = req.qs or '' headers = req.inheaders.items() rfile = req.rfile prev = None @@ -40,7 +40,7 @@ class NativeGateway(wsgiserver.Gateway): redirections = [] while True: request, response = app.get_serving( - local, remote, scheme, "HTTP/1.1") + local, remote, scheme, 'HTTP/1.1') request.multithread = True request.multiprocess = False request.app = app @@ -60,17 +60,17 @@ class NativeGateway(wsgiserver.Gateway): if not self.recursive: if ir.path in redirections: raise RuntimeError( - "InternalRedirector visited the same " - "URL twice: %r" % ir.path) + 'InternalRedirector visited the same ' + 'URL twice: %r' % ir.path) else: # Add the *previous* path_info + qs to # redirections. if qs: - qs = "?" + qs + qs = '?' + qs redirections.append(sn + path + qs) # Munge environment and try again. - method = "GET" + method = 'GET' path = ir.path qs = ir.query_string rfile = io.BytesIO() @@ -91,7 +91,7 @@ class NativeGateway(wsgiserver.Gateway): req = self.req # Set response status - req.status = str(status or "500 Server Error") + req.status = str(status or '500 Server Error') # Set response headers for header, value in headers: diff --git a/cherrypy/_cpreqbody.py b/cherrypy/_cpreqbody.py index a55e0abc..aa5cfe3d 100644 --- a/cherrypy/_cpreqbody.py +++ b/cherrypy/_cpreqbody.py @@ -169,8 +169,8 @@ def process_urlencoded(entity): break else: raise cherrypy.HTTPError( - 400, "The request entity could not be decoded. The following " - "charsets were attempted: %s" % repr(entity.attempt_charsets)) + 400, 'The request entity could not be decoded. The following ' + 'charsets were attempted: %s' % repr(entity.attempt_charsets)) # Now that all values have been successfully parsed and decoded, # apply them to the entity.params dict. @@ -185,7 +185,7 @@ def process_urlencoded(entity): def process_multipart(entity): """Read all multipart parts into entity.parts.""" - ib = "" + ib = '' if 'boundary' in entity.content_type.params: # http://tools.ietf.org/html/rfc2046#section-5.1.1 # "The grammar for parameters on the Content-type field is such that it @@ -193,7 +193,7 @@ def process_multipart(entity): # on the Content-type line" ib = entity.content_type.params['boundary'].strip('"') - if not re.match("^[ -~]{0,200}[!-~]$", ib): + if not re.match('^[ -~]{0,200}[!-~]$', ib): raise ValueError('Invalid boundary in multipart form: %r' % (ib,)) ib = ('--' + ib).encode('ascii') @@ -428,7 +428,7 @@ class Entity(object): # Copy the class 'attempt_charsets', prepending any Content-Type # charset - dec = self.content_type.params.get("charset", None) + dec = self.content_type.params.get('charset', None) if dec: self.attempt_charsets = [dec] + [c for c in self.attempt_charsets if c != dec] @@ -469,8 +469,8 @@ class Entity(object): # The 'type' attribute is deprecated in 3.2; remove it in 3.3. type = property( lambda self: self.content_type, - doc="A deprecated alias for " - ":attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`." + doc='A deprecated alias for ' + ':attr:`content_type<cherrypy._cpreqbody.Entity.content_type>`.' ) def read(self, size=None, fp_out=None): @@ -536,8 +536,8 @@ class Entity(object): else: raise cherrypy.HTTPError( 400, - "The request entity could not be decoded. The following " - "charsets were attempted: %s" % repr(self.attempt_charsets) + 'The request entity could not be decoded. The following ' + 'charsets were attempted: %s' % repr(self.attempt_charsets) ) def process(self): @@ -625,25 +625,25 @@ class Part(Entity): line = fp.readline() if not line: # No more data--illegal end of headers - raise EOFError("Illegal end of headers.") + raise EOFError('Illegal end of headers.') if line == ntob('\r\n'): # Normal end of headers break if not line.endswith(ntob('\r\n')): - raise ValueError("MIME requires CRLF terminators: %r" % line) + raise ValueError('MIME requires CRLF terminators: %r' % line) if line[0] in ntob(' \t'): # It's a continuation line. v = line.strip().decode('ISO-8859-1') else: - k, v = line.split(ntob(":"), 1) + k, v = line.split(ntob(':'), 1) k = k.strip().decode('ISO-8859-1') v = v.strip().decode('ISO-8859-1') existing = headers.get(k) if existing: - v = ", ".join((existing, v)) + v = ', '.join((existing, v)) headers[k] = v return headers @@ -658,16 +658,16 @@ class Part(Entity): object that supports the 'write' method; all bytes read will be written to the fp, and that fp is returned. """ - endmarker = self.boundary + ntob("--") - delim = ntob("") + endmarker = self.boundary + ntob('--') + delim = ntob('') prev_lf = True lines = [] seen = 0 while True: line = self.fp.readline(1 << 16) if not line: - raise EOFError("Illegal end of multipart body.") - if line.startswith(ntob("--")) and prev_lf: + raise EOFError('Illegal end of multipart body.') + if line.startswith(ntob('--')) and prev_lf: strippedline = line.strip() if strippedline == self.boundary: break @@ -677,16 +677,16 @@ class Part(Entity): line = delim + line - if line.endswith(ntob("\r\n")): - delim = ntob("\r\n") + if line.endswith(ntob('\r\n')): + delim = ntob('\r\n') line = line[:-2] prev_lf = True - elif line.endswith(ntob("\n")): - delim = ntob("\n") + elif line.endswith(ntob('\n')): + delim = ntob('\n') line = line[:-1] prev_lf = True else: - delim = ntob("") + delim = ntob('') prev_lf = False if fp_out is None: @@ -839,7 +839,7 @@ class SizedReader: if e.__class__.__name__ == 'MaxSizeExceeded': # Post data is too big raise cherrypy.HTTPError( - 413, "Maximum request length: %r" % e.args[1]) + 413, 'Maximum request length: %r' % e.args[1]) else: raise if not data: @@ -915,23 +915,23 @@ class SizedReader: v = line.strip() else: try: - k, v = line.split(ntob(":"), 1) + k, v = line.split(ntob(':'), 1) except ValueError: - raise ValueError("Illegal header line.") + raise ValueError('Illegal header line.') k = k.strip().title() v = v.strip() if k in comma_separated_headers: existing = self.trailers.get(envname) if existing: - v = ntob(", ").join((existing, v)) + v = ntob(', ').join((existing, v)) self.trailers[k] = v except Exception: e = sys.exc_info()[1] if e.__class__.__name__ == 'MaxSizeExceeded': # Post data is too big raise cherrypy.HTTPError( - 413, "Maximum request length: %r" % e.args[1]) + 413, 'Maximum request length: %r' % e.args[1]) else: raise diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py index 81771497..d59ad1ae 100644 --- a/cherrypy/_cprequest.py +++ b/cherrypy/_cprequest.py @@ -41,11 +41,11 @@ class Hook(object): self.callback = callback if failsafe is None: - failsafe = getattr(callback, "failsafe", False) + failsafe = getattr(callback, 'failsafe', False) self.failsafe = failsafe if priority is None: - priority = getattr(callback, "priority", 50) + priority = getattr(callback, 'priority', 50) self.priority = priority self.kwargs = kwargs @@ -64,10 +64,10 @@ class Hook(object): def __repr__(self): cls = self.__class__ - return ("%s.%s(callback=%r, failsafe=%r, priority=%r, %s)" + return ('%s.%s(callback=%r, failsafe=%r, priority=%r, %s)' % (cls.__module__, cls.__name__, self.callback, self.failsafe, self.priority, - ", ".join(['%s=%r' % (k, v) + ', '.join(['%s=%r' % (k, v) for k, v in self.kwargs.items()]))) @@ -124,7 +124,7 @@ class HookMap(dict): def __repr__(self): cls = self.__class__ - return "%s.%s(points=%r)" % ( + return '%s.%s(points=%r)' % ( cls.__module__, cls.__name__, copykeys(self) @@ -138,7 +138,7 @@ def hooks_namespace(k, v): # Use split again to allow multiple hooks for a single # hookpoint per path (e.g. "hooks.before_handler.1"). # Little-known fact you only get from reading source ;) - hookpoint = k.split(".", 1)[0] + hookpoint = k.split('.', 1)[0] if isinstance(v, text_or_bytes): v = cherrypy.lib.attributes(v) if not isinstance(v, Hook): @@ -199,23 +199,23 @@ class Request(object): unless we are processing an InternalRedirect.""" # Conversation/connection attributes - local = httputil.Host("127.0.0.1", 80) - "An httputil.Host(ip, port, hostname) object for the server socket." + local = httputil.Host('127.0.0.1', 80) + 'An httputil.Host(ip, port, hostname) object for the server socket.' - remote = httputil.Host("127.0.0.1", 1111) - "An httputil.Host(ip, port, hostname) object for the client socket." + remote = httputil.Host('127.0.0.1', 1111) + 'An httputil.Host(ip, port, hostname) object for the client socket.' - scheme = "http" + scheme = 'http' """ The protocol used between client and server. In most cases, this will be either 'http' or 'https'.""" - server_protocol = "HTTP/1.1" + server_protocol = 'HTTP/1.1' """ The HTTP version for which the HTTP server is at least conditionally compliant.""" - base = "" + base = '' """The (scheme://host) portion of the requested URL. In some cases (e.g. when proxying via mod_rewrite), this may contain path segments which cherrypy.url uses when constructing url's, but @@ -223,13 +223,13 @@ class Request(object): MUST NOT end in a slash.""" # Request-Line attributes - request_line = "" + request_line = '' """ The complete Request-Line received from the client. This is a single string consisting of the request method, URI, and protocol version (joined by spaces). Any final CRLF is removed.""" - method = "GET" + method = 'GET' """ Indicates the HTTP method to be performed on the resource identified by the Request-URI. Common methods include GET, HEAD, POST, PUT, and @@ -237,7 +237,7 @@ class Request(object): servers and gateways may restrict the set of allowable methods. CherryPy applications SHOULD restrict the set (on a per-URI basis).""" - query_string = "" + query_string = '' """ The query component of the Request-URI, a string of information to be interpreted by the resource. The query portion of a URI follows the @@ -312,7 +312,7 @@ class Request(object): If True, the rfile (if any) is automatically read and parsed, and the result placed into request.params or request.body.""" - methods_with_bodies = ("POST", "PUT") + methods_with_bodies = ('POST', 'PUT') """ A sequence of HTTP methods for which CherryPy will automatically attempt to read a body from the rfile. If you are going to change @@ -341,7 +341,7 @@ class Request(object): to a hierarchical arrangement of objects, starting at request.app.root. See help(cherrypy.dispatch) for more information.""" - script_name = "" + script_name = '' """ The 'mount point' of the application which is handling this request. @@ -349,7 +349,7 @@ class Request(object): the root of the URI, it MUST be an empty string (not "/"). """ - path_info = "/" + path_info = '/' """ The 'relative path' portion of the Request-URI. This is relative to the script_name ('mount point') of the application which is @@ -468,15 +468,15 @@ class Request(object): This is useful when debugging a live server with hung requests.""" namespaces = _cpconfig.NamespaceSet( - **{"hooks": hooks_namespace, - "request": request_namespace, - "response": response_namespace, - "error_page": error_page_namespace, - "tools": cherrypy.tools, + **{'hooks': hooks_namespace, + 'request': request_namespace, + 'response': response_namespace, + 'error_page': error_page_namespace, + 'tools': cherrypy.tools, }) - def __init__(self, local_host, remote_host, scheme="http", - server_protocol="HTTP/1.1"): + def __init__(self, local_host, remote_host, scheme='http', + server_protocol='HTTP/1.1'): """Populate a new Request object. local_host should be an httputil.Host object with the server info. @@ -544,7 +544,7 @@ class Request(object): self.error_response = cherrypy.HTTPError(500).set_response self.method = method - path = path or "/" + path = path or '/' self.query_string = query_string or '' self.params = {} @@ -600,11 +600,11 @@ class Request(object): if self.show_tracebacks: body = format_exc() else: - body = "" + body = '' r = bare_error(body) response.output_status, response.header_list, response.body = r - if self.method == "HEAD": + if self.method == 'HEAD': # HEAD requests MUST NOT return a message-body in the response. response.body = [] @@ -696,8 +696,8 @@ class Request(object): self.query_string, encoding=self.query_string_encoding) except UnicodeDecodeError: raise cherrypy.HTTPError( - 404, "The given query string could not be processed. Query " - "strings for this resource must be encoded with %r." % + 404, 'The given query string could not be processed. Query ' + 'strings for this resource must be encoded with %r.' % self.query_string_encoding) # Python 2 only: keyword arguments must be byte strings (type 'str'). @@ -722,7 +722,7 @@ class Request(object): # (AFAIK, only Konqueror does that), only the last one will # remain in headers (but they will be correctly stored in # request.cookie). - if "=?" in value: + if '=?' in value: dict.__setitem__(headers, name, httputil.decode_TEXT(value)) else: dict.__setitem__(headers, name, value) @@ -733,7 +733,7 @@ class Request(object): try: self.cookie.load(value) except CookieError: - msg = "Illegal cookie name %s" % value.split('=')[0] + msg = 'Illegal cookie name %s' % value.split('=')[0] raise cherrypy.HTTPError(400, msg) if not dict.__contains__(headers, 'Host'): @@ -746,7 +746,7 @@ class Request(object): host = dict.get(headers, 'Host') if not host: host = self.local.name or self.local.ip - self.base = "%s://%s" % (self.scheme, host) + self.base = '%s://%s' % (self.scheme, host) def get_resource(self, path): """Call a dispatcher (which sets self.handler and .config). (Core)""" @@ -754,7 +754,7 @@ class Request(object): # dispatchers can only be specified in app.config, not in _cp_config # (since custom dispatchers may not even have an app.root). dispatch = self.app.find_config( - path, "request.dispatch", self.dispatch) + path, 'request.dispatch', self.dispatch) # dispatch() should set self.handler and self.config dispatch(path) @@ -762,10 +762,10 @@ class Request(object): def handle_error(self): """Handle the last unanticipated exception. (Core)""" try: - self.hooks.run("before_error_response") + self.hooks.run('before_error_response') if self.error_response: self.error_response() - self.hooks.run("after_error_response") + self.hooks.run('after_error_response') cherrypy.serving.response.finalize() except cherrypy.HTTPRedirect: inst = sys.exc_info()[1] @@ -776,8 +776,8 @@ class Request(object): def _get_body_params(self): warnings.warn( - "body_params is deprecated in CherryPy 3.2, will be removed in " - "CherryPy 3.3.", + 'body_params is deprecated in CherryPy 3.2, will be removed in ' + 'CherryPy 3.3.', DeprecationWarning ) return self.body.params @@ -800,8 +800,8 @@ class ResponseBody(object): """The body of the HTTP response (the response entity).""" if six.PY3: - unicode_err = ("Page handlers MUST return bytes. Use tools.encode " - "if you wish to return unicode.") + unicode_err = ('Page handlers MUST return bytes. Use tools.encode ' + 'if you wish to return unicode.') def __get__(self, obj, objclass=None): if obj is None: @@ -842,7 +842,7 @@ class Response(object): """An HTTP Response, including status, headers, and body.""" - status = "" + status = '' """The HTTP Status-Code and Reason-Phrase.""" header_list = [] @@ -893,9 +893,9 @@ class Response(object): # Since we know all our keys are titled strings, we can # bypass HeaderMap.update and get a big speed boost. dict.update(self.headers, { - "Content-Type": 'text/html', - "Server": "CherryPy/" + cherrypy.__version__, - "Date": httputil.HTTPDate(self.time), + 'Content-Type': 'text/html', + 'Server': 'CherryPy/' + cherrypy.__version__, + 'Date': httputil.HTTPDate(self.time), }) self.cookie = SimpleCookie() @@ -924,9 +924,9 @@ class Response(object): headers = self.headers - self.status = "%s %s" % (code, reason) + self.status = '%s %s' % (code, reason) self.output_status = ntob(str(code), 'ascii') + \ - ntob(" ") + headers.encode(reason) + ntob(' ') + headers.encode(reason) if self.stream: # The upshot: wsgiserver will chunk the response if @@ -939,7 +939,7 @@ class Response(object): # and 304 (not modified) responses MUST NOT # include a message-body." dict.pop(headers, 'Content-Length', None) - self.body = ntob("") + self.body = ntob('') else: # Responses which are not streamed should have a Content-Length, # but allow user code to set Content-Length if desired. @@ -952,13 +952,13 @@ class Response(object): cookie = self.cookie.output() if cookie: - for line in cookie.split("\n"): - if line.endswith("\r"): + for line in cookie.split('\n'): + if line.endswith('\r'): # Python 2.4 emits cookies joined by LF but 2.5+ by CRLF. line = line[:-1] - name, value = line.split(": ", 1) + name, value = line.split(': ', 1) if isinstance(name, six.text_type): - name = name.encode("ISO-8859-1") + name = name.encode('ISO-8859-1') if isinstance(value, six.text_type): value = headers.encode(value) h.append((name, value)) diff --git a/cherrypy/_cpserver.py b/cherrypy/_cpserver.py index 2e6e48de..9fed02fa 100644 --- a/cherrypy/_cpserver.py +++ b/cherrypy/_cpserver.py @@ -35,7 +35,7 @@ class Server(ServerAdapter): if value == '': raise ValueError("The empty string ('') is not an allowed value. " "Use '0.0.0.0' instead to listen on all active " - "interfaces (INADDR_ANY).") + 'interfaces (INADDR_ANY).') self._socket_host = value socket_host = property( _get_socket_host, @@ -189,9 +189,9 @@ class Server(ServerAdapter): self.socket_host, self.socket_port = value self.socket_file = None except ValueError: - raise ValueError("bind_addr must be a (host, port) tuple " - "(for TCP sockets) or a string (for Unix " - "domain sockets), not %r" % value) + raise ValueError('bind_addr must be a (host, port) tuple ' + '(for TCP sockets) or a string (for Unix ' + 'domain sockets), not %r' % value) bind_addr = property( _get_bind_addr, _set_bind_addr, @@ -215,12 +215,12 @@ class Server(ServerAdapter): port = self.socket_port if self.ssl_certificate: - scheme = "https" + scheme = 'https' if port != 443: - host += ":%s" % port + host += ':%s' % port else: - scheme = "http" + scheme = 'http' if port != 80: - host += ":%s" % port + host += ':%s' % port - return "%s://%s" % (scheme, host) + return '%s://%s' % (scheme, host) diff --git a/cherrypy/_cpthreadinglocal.py b/cherrypy/_cpthreadinglocal.py index 874c1488..04679018 100644 --- a/cherrypy/_cpthreadinglocal.py +++ b/cherrypy/_cpthreadinglocal.py @@ -149,7 +149,7 @@ class _localbase(object): object.__setattr__(self, '_local__lock', RLock()) if args or kw and (cls.__init__ is object.__init__): - raise TypeError("Initialization arguments are not supported") + raise TypeError('Initialization arguments are not supported') # We need to create the thread dict in anticipation of # __init__ being called, to make sure we don't call it diff --git a/cherrypy/_cptools.py b/cherrypy/_cptools.py index 452cad1d..98d3b21e 100644 --- a/cherrypy/_cptools.py +++ b/cherrypy/_cptools.py @@ -50,8 +50,8 @@ def _getargs(func): _attr_error = ( - "CherryPy Tools cannot be turned on directly. Instead, turn them " - "on via config, or use them as decorators on your page handlers." + 'CherryPy Tools cannot be turned on directly. Instead, turn them ' + 'on via config, or use them as decorators on your page handlers.' ) @@ -62,7 +62,7 @@ class Tool(object): help(tool.callable) should give you more information about this Tool. """ - namespace = "tools" + namespace = 'tools' def __init__(self, point, callable, name=None, priority=50): self._point = point @@ -85,7 +85,7 @@ class Tool(object): for arg in _getargs(self.callable): setattr(self, arg, None) except (TypeError, AttributeError): - if hasattr(self.callable, "__call__"): + if hasattr(self.callable, '__call__'): for arg in _getargs(self.callable.__call__): setattr(self, arg, None) # IronPython 1.0 raises NotImplementedError because @@ -109,8 +109,8 @@ class Tool(object): if self._name in tm: conf.update(tm[self._name]) - if "on" in conf: - del conf["on"] + if 'on' in conf: + del conf['on'] return conf @@ -125,15 +125,15 @@ class Tool(object): return cherrypy.request.base """ if args: - raise TypeError("The %r Tool does not accept positional " - "arguments; you must use keyword arguments." + raise TypeError('The %r Tool does not accept positional ' + 'arguments; you must use keyword arguments.' % self._name) def tool_decorator(f): - if not hasattr(f, "_cp_config"): + if not hasattr(f, '_cp_config'): f._cp_config = {} - subspace = self.namespace + "." + self._name + "." - f._cp_config[subspace + "on"] = True + subspace = self.namespace + '.' + self._name + '.' + f._cp_config[subspace + 'on'] = True for k, v in kwargs.items(): f._cp_config[subspace + k] = v return f @@ -146,9 +146,9 @@ class Tool(object): method when the tool is "turned on" in config. """ conf = self._merged_args() - p = conf.pop("priority", None) + p = conf.pop('priority', None) if p is None: - p = getattr(self.callable, "priority", self._priority) + p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self.callable, priority=p, **conf) @@ -196,9 +196,9 @@ class HandlerTool(Tool): method when the tool is "turned on" in config. """ conf = self._merged_args() - p = conf.pop("priority", None) + p = conf.pop('priority', None) if p is None: - p = getattr(self.callable, "priority", self._priority) + p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self._wrapper, priority=p, **conf) @@ -296,9 +296,9 @@ class SessionTool(Tool): conf = self._merged_args() - p = conf.pop("priority", None) + p = conf.pop('priority', None) if p is None: - p = getattr(self.callable, "priority", self._priority) + p = getattr(self.callable, 'priority', self._priority) hooks.attach(self._point, self.callable, priority=p, **conf) @@ -374,7 +374,7 @@ class XMLRPCController(object): for attr in str(rpcmethod).split('.'): subhandler = getattr(subhandler, attr, None) - if subhandler and getattr(subhandler, "exposed", False): + if subhandler and getattr(subhandler, 'exposed', False): body = subhandler(*(vpath + rpcparams), **params) else: @@ -384,7 +384,7 @@ class XMLRPCController(object): # cherrypy.lib.xmlrpcutil.on_error raise Exception('method "%s" is not supported' % attr) - conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {}) + conf = cherrypy.serving.request.toolmaps['tools'].get('xmlrpc', {}) _xmlrpc.respond(body, conf.get('encoding', 'utf-8'), conf.get('allow_none', 0)) @@ -395,7 +395,7 @@ class SessionAuthTool(HandlerTool): def _setargs(self): for name in dir(cptools.SessionAuth): - if not name.startswith("__"): + if not name.startswith('__'): setattr(self, name, None) @@ -418,7 +418,7 @@ class CachingTool(Tool): """Hook caching into cherrypy.request.""" conf = self._merged_args() - p = conf.pop("priority", None) + p = conf.pop('priority', None) cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, priority=p, **conf) @@ -447,7 +447,7 @@ class Toolbox(object): cherrypy.serving.request.toolmaps[self.namespace] = map = {} def populate(k, v): - toolname, arg = k.split(".", 1) + toolname, arg = k.split('.', 1) bucket = map.setdefault(toolname, {}) bucket[arg] = v return populate @@ -457,7 +457,7 @@ class Toolbox(object): map = cherrypy.serving.request.toolmaps.get(self.namespace) if map: for name, settings in map.items(): - if settings.get("on", False): + if settings.get('on', False): tool = getattr(self, name) tool._setup() @@ -472,7 +472,7 @@ class Toolbox(object): class DeprecatedTool(Tool): _name = None - warnmsg = "This Tool is deprecated." + warnmsg = 'This Tool is deprecated.' def __init__(self, point, warnmsg=None): self.point = point @@ -490,7 +490,7 @@ class DeprecatedTool(Tool): warnings.warn(self.warnmsg) -default_toolbox = _d = Toolbox("tools") +default_toolbox = _d = Toolbox('tools') _d.session_auth = SessionAuthTool(cptools.session_auth) _d.allow = Tool('on_start_resource', cptools.allow) _d.proxy = Tool('before_request_body', cptools.proxy, priority=30) @@ -512,14 +512,14 @@ _d.caching = CachingTool('before_handler', _caching.get, 'caching') _d.expires = Tool('before_finalize', _caching.expires) _d.tidy = DeprecatedTool( 'before_finalize', - "The tidy tool has been removed from the standard distribution of " - "CherryPy. The most recent version can be found at " - "http://tools.cherrypy.org/browser.") + 'The tidy tool has been removed from the standard distribution of ' + 'CherryPy. The most recent version can be found at ' + 'http://tools.cherrypy.org/browser.') _d.nsgmls = DeprecatedTool( 'before_finalize', - "The nsgmls tool has been removed from the standard distribution of " - "CherryPy. The most recent version can be found at " - "http://tools.cherrypy.org/browser.") + 'The nsgmls tool has been removed from the standard distribution of ' + 'CherryPy. The most recent version can be found at ' + 'http://tools.cherrypy.org/browser.') _d.ignore_headers = Tool('before_request_body', cptools.ignore_headers) _d.referer = Tool('before_request_body', cptools.referer) _d.basic_auth = Tool('on_start_resource', auth.basic_auth) diff --git a/cherrypy/_cptree.py b/cherrypy/_cptree.py index c40e3b33..93ad1011 100644 --- a/cherrypy/_cptree.py +++ b/cherrypy/_cptree.py @@ -46,22 +46,22 @@ class Application(object): relative_urls = False - def __init__(self, root, script_name="", config=None): + def __init__(self, root, script_name='', config=None): self.log = _cplogging.LogManager(id(self), cherrypy.log.logger_root) self.root = root self.script_name = script_name self.wsgiapp = _cpwsgi.CPWSGIApp(self) self.namespaces = self.namespaces.copy() - self.namespaces["log"] = lambda k, v: setattr(self.log, k, v) - self.namespaces["wsgi"] = self.wsgiapp.namespace_handler + self.namespaces['log'] = lambda k, v: setattr(self.log, k, v) + self.namespaces['wsgi'] = self.wsgiapp.namespace_handler self.config = self.__class__.config.copy() if config: self.merge(config) def __repr__(self): - return "%s.%s(%r, %r)" % (self.__module__, self.__class__.__name__, + return '%s.%s(%r, %r)' % (self.__module__, self.__class__.__name__, self.root, self.script_name) script_name_doc = """The URI "mount point" for this app. A mount point @@ -86,11 +86,11 @@ class Application(object): # A `_script_name` with a value of None signals that the script name # should be pulled from WSGI environ. - return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip("/") + return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip('/') def _set_script_name(self, value): if value: - value = value.rstrip("/") + value = value.rstrip('/') self._script_name = value script_name = property(fget=_get_script_name, fset=_set_script_name, doc=script_name_doc) @@ -100,22 +100,22 @@ class Application(object): _cpconfig.merge(self.config, config) # Handle namespaces specified in config. - self.namespaces(self.config.get("/", {})) + self.namespaces(self.config.get('/', {})) def find_config(self, path, key, default=None): """Return the most-specific value for key along path, or default.""" - trail = path or "/" + trail = path or '/' while trail: nodeconf = self.config.get(trail, {}) if key in nodeconf: return nodeconf[key] - lastslash = trail.rfind("/") + lastslash = trail.rfind('/') if lastslash == -1: break - elif lastslash == 0 and trail != "/": - trail = "/" + elif lastslash == 0 and trail != '/': + trail = '/' else: trail = trail[:lastslash] @@ -172,7 +172,7 @@ class Tree(object): def __init__(self): self.apps = {} - def mount(self, root, script_name="", config=None): + def mount(self, root, script_name='', config=None): """Mount a new app from a root object, script_name, and config. root @@ -197,29 +197,29 @@ class Tree(object): if script_name is None: raise TypeError( "The 'script_name' argument may not be None. Application " - "objects may, however, possess a script_name of None (in " - "order to inpect the WSGI environ for SCRIPT_NAME upon each " - "request). You cannot mount such Applications on this Tree; " - "you must pass them to a WSGI server interface directly.") + 'objects may, however, possess a script_name of None (in ' + 'order to inpect the WSGI environ for SCRIPT_NAME upon each ' + 'request). You cannot mount such Applications on this Tree; ' + 'you must pass them to a WSGI server interface directly.') # Next line both 1) strips trailing slash and 2) maps "/" -> "". - script_name = script_name.rstrip("/") + script_name = script_name.rstrip('/') if isinstance(root, Application): app = root - if script_name != "" and script_name != app.script_name: + if script_name != '' and script_name != app.script_name: raise ValueError( - "Cannot specify a different script name and pass an " - "Application instance to cherrypy.mount") + 'Cannot specify a different script name and pass an ' + 'Application instance to cherrypy.mount') script_name = app.script_name else: app = Application(root, script_name) # If mounted at "", add favicon.ico - if (script_name == "" and root is not None - and not hasattr(root, "favicon_ico")): + if (script_name == '' and root is not None + and not hasattr(root, 'favicon_ico')): favicon = os.path.join(os.getcwd(), os.path.dirname(__file__), - "favicon.ico") + 'favicon.ico') root.favicon_ico = tools.staticfile.handler(favicon) if config: @@ -229,10 +229,10 @@ class Tree(object): return app - def graft(self, wsgi_callable, script_name=""): + def graft(self, wsgi_callable, script_name=''): """Mount a wsgi callable at the given script_name.""" # Next line both 1) strips trailing slash and 2) maps "/" -> "". - script_name = script_name.rstrip("/") + script_name = script_name.rstrip('/') self.apps[script_name] = wsgi_callable def script_name(self, path=None): @@ -252,11 +252,11 @@ class Tree(object): if path in self.apps: return path - if path == "": + if path == '': return None # Move one node up the tree and try again. - path = path[:path.rfind("/")] + path = path[:path.rfind('/')] def __call__(self, environ, start_response): # If you're calling this, then you're probably setting SCRIPT_NAME @@ -267,7 +267,7 @@ class Tree(object): 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 "/") + sn = self.script_name(path or '/') if sn is None: start_response('404 Not Found', []) return [] @@ -280,8 +280,8 @@ class Tree(object): # 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) + environ[ntou('PATH_INFO')] = path[len(sn.rstrip('/')):].decode(enc) else: environ['SCRIPT_NAME'] = sn - environ['PATH_INFO'] = path[len(sn.rstrip("/")):] + environ['PATH_INFO'] = path[len(sn.rstrip('/')):] return app(environ, start_response) diff --git a/cherrypy/_cpwsgi.py b/cherrypy/_cpwsgi.py index 29543d92..d75e8270 100644 --- a/cherrypy/_cpwsgi.py +++ b/cherrypy/_cpwsgi.py @@ -81,7 +81,7 @@ class VirtualHost(object): def __call__(self, environ, start_response): domain = environ.get('HTTP_HOST', '') if self.use_x_forwarded_host: - domain = environ.get("HTTP_X_FORWARDED_HOST", domain) + domain = environ.get('HTTP_X_FORWARDED_HOST', domain) nextapp = self.domains.get(domain) if nextapp is None: @@ -112,7 +112,7 @@ class InternalRedirector(object): # Add the *previous* path_info + qs to redirections. old_uri = sn + path if qs: - old_uri += "?" + qs + old_uri += '?' + qs redirections.append(old_uri) if not self.recursive: @@ -120,20 +120,20 @@ class InternalRedirector(object): # already new_uri = sn + ir.path if ir.query_string: - new_uri += "?" + ir.query_string + new_uri += '?' + ir.query_string if new_uri in redirections: ir.request.close() tmpl = ( - "InternalRedirector visited the same URL twice: %r" + 'InternalRedirector visited the same URL twice: %r' ) raise RuntimeError(tmpl % new_uri) # Munge the environment and try again. - environ['REQUEST_METHOD'] = "GET" + environ['REQUEST_METHOD'] = 'GET' environ['PATH_INFO'] = ir.path environ['QUERY_STRING'] = ir.query_string environ['wsgi.input'] = io.BytesIO() - environ['CONTENT_LENGTH'] = "0" + environ['CONTENT_LENGTH'] = '0' environ['cherrypy.previous_request'] = ir.request @@ -196,7 +196,7 @@ class _TrappedResponse(object): #print('trapped (started %s):' % self.started_response, tb) _cherrypy.log(tb, severity=40) if not _cherrypy.request.show_tracebacks: - tb = "" + tb = '' s, h, b = _cperror.bare_error(tb) if six.PY3: # What fun. @@ -223,7 +223,7 @@ class _TrappedResponse(object): raise if self.started_response: - return ntob("").join(b) + return ntob('').join(b) else: return b @@ -248,16 +248,16 @@ class AppResponse(object): outstatus = r.output_status if not isinstance(outstatus, bytes): - raise TypeError("response.output_status is not a byte string.") + raise TypeError('response.output_status is not a byte string.') outheaders = [] for k, v in r.header_list: if not isinstance(k, bytes): - tmpl = "response.header_list key %r is not a byte string." + tmpl = 'response.header_list key %r is not a byte string.' raise TypeError(tmpl % k) if not isinstance(v, bytes): tmpl = ( - "response.header_list value %r is not a byte string." + 'response.header_list value %r is not a byte string.' ) raise TypeError(tmpl % v) outheaders.append((k, v)) @@ -320,7 +320,7 @@ class AppResponse(object): env('REMOTE_HOST', ''), ) scheme = env('wsgi.url_scheme') - sproto = env('ACTUAL_SERVER_PROTOCOL', "HTTP/1.1") + sproto = env('ACTUAL_SERVER_PROTOCOL', 'HTTP/1.1') request, resp = self.cpapp.get_serving(local, remote, scheme, sproto) # LOGON_USER is served by IIS, and is the name of the @@ -365,7 +365,7 @@ class AppResponse(object): old_enc = self.environ.get('wsgi.url_encoding', 'ISO-8859-1') new_enc = self.cpapp.find_config( self.environ.get('PATH_INFO', ''), - "request.uri_encoding", 'utf-8', + 'request.uri_encoding', 'utf-8', ) if new_enc.lower() == old_enc.lower(): return @@ -389,9 +389,9 @@ class AppResponse(object): # We assume all incoming header keys are uppercase already. if cgiName in self.headerNames: yield self.headerNames[cgiName], environ[cgiName] - elif cgiName[:5] == "HTTP_": + elif cgiName[:5] == 'HTTP_': # Hackish attempt at recovering original header names. - translatedHeader = cgiName[5:].replace("_", "-") + translatedHeader = cgiName[5:].replace('_', '-') yield translatedHeader, environ[cgiName] @@ -452,16 +452,16 @@ class CPWSGIApp(object): def namespace_handler(self, k, v): """Config handler for the 'wsgi' namespace.""" - if k == "pipeline": + if k == 'pipeline': # Note this allows multiple 'wsgi.pipeline' config entries # (but each entry will be processed in a 'random' order). # It should also allow developers to set default middleware # in code (passed to self.__init__) that deployers can add to # (but not remove) via config. self.pipeline.extend(v) - elif k == "response_class": + elif k == 'response_class': self.response_class = v else: - name, arg = k.split(".", 1) + name, arg = k.split('.', 1) bucket = self.config.setdefault(name, {}) bucket[arg] = v diff --git a/cherrypy/_cpwsgi_server.py b/cherrypy/_cpwsgi_server.py index 874e2e9f..d03a0770 100644 --- a/cherrypy/_cpwsgi_server.py +++ b/cherrypy/_cpwsgi_server.py @@ -66,5 +66,5 @@ class CPWSGIServer(wsgiserver.CherryPyWSGIServer): self.stats['Enabled'] = getattr( self.server_adapter, 'statistics', False) - def error_log(self, msg="", level=20, traceback=False): + def error_log(self, msg='', level=20, traceback=False): cherrypy.engine.log(msg, level, traceback) diff --git a/cherrypy/_helper.py b/cherrypy/_helper.py index 23357bc8..5875ec0f 100644 --- a/cherrypy/_helper.py +++ b/cherrypy/_helper.py @@ -18,10 +18,10 @@ def expose(func=None, alias=None): func.exposed = True if alias is not None: if isinstance(alias, text_or_bytes): - parents[alias.replace(".", "_")] = func + parents[alias.replace('.', '_')] = func else: for a in alias: - parents[a.replace(".", "_")] = func + parents[a.replace('.', '_')] = func return func import sys @@ -191,7 +191,7 @@ def popargs(*args, **kwargs): return decorated -def url(path="", qs="", script_name=None, base=None, relative=None): +def url(path='', qs='', script_name=None, base=None, relative=None): """Create an absolute URL for the given path. If 'path' starts with a slash ('/'), this will return @@ -224,7 +224,7 @@ def url(path="", qs="", script_name=None, base=None, relative=None): qs = '?' + qs if cherrypy.request.app: - if not path.startswith("/"): + if not path.startswith('/'): # Append/remove trailing slash from path_info as needed # (this is to support mistyped URL's without redirecting; # if you want to redirect, use tools.trailing_slash). @@ -236,7 +236,7 @@ def url(path="", qs="", script_name=None, base=None, relative=None): if pi.endswith('/') and pi != '/': pi = pi[:-1] - if path == "": + if path == '': path = pi else: path = _urljoin(pi, path) @@ -255,7 +255,7 @@ def url(path="", qs="", script_name=None, base=None, relative=None): if base is None: base = cherrypy.server.base() - path = (script_name or "") + path + path = (script_name or '') + path newurl = base + path + qs if './' in newurl: @@ -273,7 +273,7 @@ def url(path="", qs="", script_name=None, base=None, relative=None): # At this point, we should have a fully-qualified absolute URL. if relative is None: - relative = getattr(cherrypy.request.app, "relative_urls", False) + relative = getattr(cherrypy.request.app, 'relative_urls', False) # See http://www.ietf.org/rfc/rfc2396.txt if relative == 'server': diff --git a/cherrypy/daemon.py b/cherrypy/daemon.py index e5e9a989..772b2fc1 100755 --- a/cherrypy/daemon.py +++ b/cherrypy/daemon.py @@ -13,7 +13,7 @@ def start(configfiles=None, daemonize=False, environment=None, """Subscribe all engine plugins and start the engine.""" sys.path = [''] + sys.path for i in imports or []: - exec("import %s" % i) + exec('import %s' % i) for c in configfiles or []: cherrypy.config.update(c) @@ -37,14 +37,14 @@ def start(configfiles=None, daemonize=False, environment=None, if pidfile: plugins.PIDFile(engine, pidfile).subscribe() - if hasattr(engine, "signal_handler"): + if hasattr(engine, 'signal_handler'): engine.signal_handler.subscribe() - if hasattr(engine, "console_control_handler"): + if hasattr(engine, 'console_control_handler'): engine.console_control_handler.subscribe() if (fastcgi and (scgi or cgi)) or (scgi and cgi): - cherrypy.log.error("You may only specify one of the cgi, fastcgi, and " - "scgi options.", 'ENGINE') + cherrypy.log.error('You may only specify one of the cgi, fastcgi, and ' + 'scgi options.', 'ENGINE') sys.exit(1) elif fastcgi or scgi or cgi: # Turn off autoreload when using *cgi. @@ -76,25 +76,25 @@ def run(): from optparse import OptionParser p = OptionParser() - p.add_option('-c', '--config', action="append", dest='config', - help="specify config file(s)") - p.add_option('-d', action="store_true", dest='daemonize', - help="run the server as a daemon") + p.add_option('-c', '--config', action='append', dest='config', + help='specify config file(s)') + p.add_option('-d', action='store_true', dest='daemonize', + help='run the server as a daemon') p.add_option('-e', '--environment', dest='environment', default=None, - help="apply the given config environment") - p.add_option('-f', action="store_true", dest='fastcgi', - help="start a fastcgi server instead of the default HTTP " - "server") - p.add_option('-s', action="store_true", dest='scgi', - help="start a scgi server instead of the default HTTP server") - p.add_option('-x', action="store_true", dest='cgi', - help="start a cgi server instead of the default HTTP server") - p.add_option('-i', '--import', action="append", dest='imports', - help="specify modules to import") + help='apply the given config environment') + p.add_option('-f', action='store_true', dest='fastcgi', + help='start a fastcgi server instead of the default HTTP ' + 'server') + p.add_option('-s', action='store_true', dest='scgi', + help='start a scgi server instead of the default HTTP server') + p.add_option('-x', action='store_true', dest='cgi', + help='start a cgi server instead of the default HTTP server') + p.add_option('-i', '--import', action='append', dest='imports', + help='specify modules to import') p.add_option('-p', '--pidfile', dest='pidfile', default=None, - help="store the process id in the given file") - p.add_option('-P', '--Path', action="append", dest='Path', - help="add the given paths to sys.path") + help='store the process id in the given file') + p.add_option('-P', '--Path', action='append', dest='Path', + help='add the given paths to sys.path') options, args = p.parse_args() if options.Path: diff --git a/cherrypy/lib/__init__.py b/cherrypy/lib/__init__.py index 7b82e89a..af08028f 100644 --- a/cherrypy/lib/__init__.py +++ b/cherrypy/lib/__init__.py @@ -77,9 +77,9 @@ def file_generator_limited(fileobj, count, chunk_size=65536): def set_vary_header(response, header_name): - "Add a Vary header to a response" - varies = response.headers.get("Vary", "") - varies = [x.strip() for x in varies.split(",") if x.strip()] + 'Add a Vary header to a response' + varies = response.headers.get('Vary', '') + varies = [x.strip() for x in varies.split(',') if x.strip()] if header_name not in varies: varies.append(header_name) - response.headers['Vary'] = ", ".join(varies) + response.headers['Vary'] = ', '.join(varies) diff --git a/cherrypy/lib/auth.py b/cherrypy/lib/auth.py index 71591aaa..34ad6886 100644 --- a/cherrypy/lib/auth.py +++ b/cherrypy/lib/auth.py @@ -22,25 +22,25 @@ def check_auth(users, encrypt=None, realm=None): if not isinstance(users, dict): raise ValueError( - "Authentication users must be a dictionary") + 'Authentication users must be a dictionary') # fetch the user password - password = users.get(ah["username"], None) + password = users.get(ah['username'], None) except TypeError: # returns a password (encrypted or clear text) - password = users(ah["username"]) + password = users(ah['username']) else: if not isinstance(users, dict): - raise ValueError("Authentication users must be a dictionary") + raise ValueError('Authentication users must be a dictionary') # fetch the user password - password = users.get(ah["username"], None) + password = users.get(ah['username'], None) # validate the authorization by re-computing it here # and compare it with what the user-agent provided if httpauth.checkResponse(ah, password, method=request.method, encrypt=encrypt, realm=realm): - request.login = ah["username"] + request.login = ah['username'] return True request.login = False @@ -72,7 +72,7 @@ def basic_auth(realm, users, encrypt=None, debug=False): 'www-authenticate'] = httpauth.basicAuth(realm) raise cherrypy.HTTPError( - 401, "You are not authorized to access that resource") + 401, 'You are not authorized to access that resource') def digest_auth(realm, users, debug=False): @@ -94,4 +94,4 @@ def digest_auth(realm, users, debug=False): 'www-authenticate'] = httpauth.digestAuth(realm) raise cherrypy.HTTPError( - 401, "You are not authorized to access that resource") + 401, 'You are not authorized to access that resource') diff --git a/cherrypy/lib/auth_basic.py b/cherrypy/lib/auth_basic.py index 8512cc6f..c9c9bd55 100644 --- a/cherrypy/lib/auth_basic.py +++ b/cherrypy/lib/auth_basic.py @@ -87,4 +87,4 @@ def basic_auth(realm, checkpassword, debug=False): cherrypy.serving.response.headers[ 'www-authenticate'] = 'Basic realm="%s"' % realm raise cherrypy.HTTPError( - 401, "You are not authorized to access that resource") + 401, 'You are not authorized to access that resource') diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py index 6dc5abf6..0e767e95 100644 --- a/cherrypy/lib/auth_digest.py +++ b/cherrypy/lib/auth_digest.py @@ -143,7 +143,7 @@ class HttpDigestAuthorization (object): def __init__(self, auth_header, http_method, debug=False): self.http_method = http_method self.debug = debug - scheme, params = auth_header.split(" ", 1) + scheme, params = auth_header.split(' ', 1) self.scheme = scheme.lower() if self.scheme != 'digest': raise ValueError('Authorization scheme is not "Digest"') @@ -181,7 +181,7 @@ class HttpDigestAuthorization (object): ) if not has_reqd: raise ValueError( - self.errmsg("Not all required parameters are present.")) + self.errmsg('Not all required parameters are present.')) if self.qop: if self.qop not in valid_qops: @@ -189,13 +189,13 @@ class HttpDigestAuthorization (object): self.errmsg("Unsupported value for qop: '%s'" % self.qop)) if not (self.cnonce and self.nc): raise ValueError( - self.errmsg("If qop is sent then " - "cnonce and nc MUST be present")) + self.errmsg('If qop is sent then ' + 'cnonce and nc MUST be present')) else: if self.cnonce or self.nc: raise ValueError( - self.errmsg("If qop is not sent, " - "neither cnonce nor nc can be present")) + self.errmsg('If qop is not sent, ' + 'neither cnonce nor nc can be present')) def __str__(self): return 'authorization : %s' % self.auth_header @@ -240,7 +240,7 @@ class HttpDigestAuthorization (object): except ValueError: # int() error pass if self.debug: - TRACE("nonce is stale") + TRACE('nonce is stale') return True def HA2(self, entity_body=''): @@ -252,14 +252,14 @@ class HttpDigestAuthorization (object): # # If the "qop" value is "auth-int", then A2 is: # A2 = method ":" digest-uri-value ":" H(entity-body) - if self.qop is None or self.qop == "auth": + if self.qop is None or self.qop == 'auth': a2 = '%s:%s' % (self.http_method, self.uri) - elif self.qop == "auth-int": - a2 = "%s:%s:%s" % (self.http_method, self.uri, H(entity_body)) + elif self.qop == 'auth-int': + a2 = '%s:%s:%s' % (self.http_method, self.uri, H(entity_body)) else: # in theory, this should never happen, since I validate qop in # __init__() - raise ValueError(self.errmsg("Unrecognized value for qop!")) + raise ValueError(self.errmsg('Unrecognized value for qop!')) return H(a2) def request_digest(self, ha1, entity_body=''): @@ -280,10 +280,10 @@ class HttpDigestAuthorization (object): ha2 = self.HA2(entity_body) # Request-Digest -- RFC 2617 3.2.2.1 if self.qop: - req = "%s:%s:%s:%s:%s" % ( + req = '%s:%s:%s:%s:%s' % ( self.nonce, self.nc, self.cnonce, self.qop, ha2) else: - req = "%s:%s" % (self.nonce, ha2) + req = '%s:%s' % (self.nonce, ha2) # RFC 2617 3.2.2.2 # @@ -353,7 +353,7 @@ def digest_auth(realm, get_ha1, key, debug=False): nonce_is_stale = False if auth_header is not None: with cherrypy.HTTPError.handle(ValueError, 400, - "The Authorization header could not be parsed."): + 'The Authorization header could not be parsed.'): auth = HttpDigestAuthorization( auth_header, request.method, debug=debug) @@ -369,7 +369,7 @@ def digest_auth(realm, get_ha1, key, debug=False): digest = auth.request_digest(ha1, entity_body=request.body) if digest == auth.response: # authenticated if debug: - TRACE("digest matches auth.response") + TRACE('digest matches auth.response') # Now check if nonce is stale. # The choice of ten minutes' lifetime for nonce is somewhat # arbitrary @@ -377,7 +377,7 @@ def digest_auth(realm, get_ha1, key, debug=False): if not nonce_is_stale: request.login = auth.username if debug: - TRACE("authentication of %s successful" % + TRACE('authentication of %s successful' % auth.username) return @@ -387,4 +387,4 @@ def digest_auth(realm, get_ha1, key, debug=False): TRACE(header) cherrypy.serving.response.headers['WWW-Authenticate'] = header raise cherrypy.HTTPError( - 401, "You are not authorized to access that resource") + 401, 'You are not authorized to access that resource') diff --git a/cherrypy/lib/caching.py b/cherrypy/lib/caching.py index 3f49259a..f363a671 100644 --- a/cherrypy/lib/caching.py +++ b/cherrypy/lib/caching.py @@ -265,7 +265,7 @@ class MemoryCache(Cache): self.store.pop(uri, None) -def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs): +def get(invalid_methods=('POST', 'PUT', 'DELETE'), debug=False, **kwargs): """Try to obtain cached output. If fresh enough, raise HTTPError(304). If POST, PUT, or DELETE: @@ -291,9 +291,9 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs): request = cherrypy.serving.request response = cherrypy.serving.response - if not hasattr(cherrypy, "_cache"): + if not hasattr(cherrypy, '_cache'): # Make a process-wide Cache object. - cherrypy._cache = kwargs.pop("cache_class", MemoryCache)() + cherrypy._cache = kwargs.pop('cache_class', MemoryCache)() # Take all remaining kwargs and set them on the Cache object. for k, v in kwargs.items(): @@ -328,7 +328,7 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs): if directive == 'max-age': if len(atoms) != 1 or not atoms[0].isdigit(): raise cherrypy.HTTPError( - 400, "Invalid Cache-Control header") + 400, 'Invalid Cache-Control header') max_age = int(atoms[0]) break elif directive == 'no-cache': @@ -359,7 +359,7 @@ def get(invalid_methods=("POST", "PUT", "DELETE"), debug=False, **kwargs): dict.__setitem__(rh, k, dict.__getitem__(h, k)) # Add the required Age header - response.headers["Age"] = str(age) + response.headers['Age'] = str(age) try: # Note that validate_since depends on a Last-Modified header; @@ -457,14 +457,14 @@ def expires(secs=0, force=False, debug=False): secs = (86400 * secs.days) + secs.seconds if secs == 0: - if force or ("Pragma" not in headers): - headers["Pragma"] = "no-cache" + if force or ('Pragma' not in headers): + headers['Pragma'] = 'no-cache' if cherrypy.serving.request.protocol >= (1, 1): - if force or "Cache-Control" not in headers: - headers["Cache-Control"] = "no-cache, must-revalidate" + if force or 'Cache-Control' not in headers: + headers['Cache-Control'] = 'no-cache, must-revalidate' # Set an explicit Expires date in the past. expiry = httputil.HTTPDate(1169942400.0) else: expiry = httputil.HTTPDate(response.time + secs) - if force or "Expires" not in headers: - headers["Expires"] = expiry + if force or 'Expires' not in headers: + headers['Expires'] = expiry diff --git a/cherrypy/lib/covercp.py b/cherrypy/lib/covercp.py index 5f8da630..cf1743cb 100644 --- a/cherrypy/lib/covercp.py +++ b/cherrypy/lib/covercp.py @@ -30,7 +30,7 @@ import cherrypy from cherrypy._cpcompat import quote_plus -localFile = os.path.join(os.path.dirname(__file__), "coverage.cache") +localFile = os.path.join(os.path.dirname(__file__), 'coverage.cache') the_coverage = None try: @@ -46,8 +46,8 @@ except ImportError: import warnings warnings.warn( - "No code coverage will be performed; " - "coverage.py could not be imported.") + 'No code coverage will be performed; ' + 'coverage.py could not be imported.') def start(): pass @@ -197,7 +197,7 @@ def _percent(statements, missing): return 0 -def _show_branch(root, base, path, pct=0, showpct=False, exclude="", +def _show_branch(root, base, path, pct=0, showpct=False, exclude='', coverage=the_coverage): # Show the directory name and any of our children @@ -208,7 +208,7 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude="", if newpath.lower().startswith(base): relpath = newpath[len(base):] - yield "| " * relpath.count(os.sep) + yield '| ' * relpath.count(os.sep) yield ( "<a class='directory' " "href='menu?base=%s&exclude=%s'>%s</a>\n" % @@ -229,7 +229,7 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude="", for name in files: newpath = os.path.join(path, name) - pc_str = "" + pc_str = '' if showpct: try: _, statements, _, missing, _ = coverage.analysis2(newpath) @@ -238,13 +238,13 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude="", pass else: pc = _percent(statements, missing) - pc_str = ("%3d%% " % pc).replace(' ', ' ') + pc_str = ('%3d%% ' % pc).replace(' ', ' ') if pc < float(pct) or pc == -1: pc_str = "<span class='fail'>%s</span>" % pc_str else: pc_str = "<span class='pass'>%s</span>" % pc_str - yield TEMPLATE_ITEM % ("| " * (relpath.count(os.sep) + 1), + yield TEMPLATE_ITEM % ('| ' * (relpath.count(os.sep) + 1), pc_str, newpath, name) @@ -264,8 +264,8 @@ def _graft(path, tree): break atoms.append(tail) atoms.append(p) - if p != "/": - atoms.append("/") + if p != '/': + atoms.append('/') atoms.reverse() for node in atoms: @@ -299,7 +299,7 @@ class CoverStats(object): return TEMPLATE_FRAMESET % self.root.lower() @cherrypy.expose - def menu(self, base="/", pct="50", showpct="", + def menu(self, base='/', pct='50', showpct='', exclude=r'python\d\.\d|test|tut\d|tutorial'): # The coverage module uses all-lower-case names. @@ -310,36 +310,36 @@ class CoverStats(object): # Start by showing links for parent paths yield "<div id='crumbs'>" - path = "" + path = '' atoms = base.split(os.sep) atoms.pop() for atom in atoms: path += atom + os.sep yield ("<a href='menu?base=%s&exclude=%s'>%s</a> %s" % (path, quote_plus(exclude), atom, os.sep)) - yield "</div>" + yield '</div>' yield "<div id='tree'>" # Then display the tree tree = get_tree(base, exclude, self.coverage) if not tree: - yield "<p>No modules covered.</p>" + yield '<p>No modules covered.</p>' else: - for chunk in _show_branch(tree, base, "/", pct, + for chunk in _show_branch(tree, base, '/', pct, showpct == 'checked', exclude, coverage=self.coverage): yield chunk - yield "</div>" - yield "</body></html>" + yield '</div>' + yield '</body></html>' def annotated_file(self, filename, statements, excluded, missing): source = open(filename, 'r') buffer = [] for lineno, line in enumerate(source.readlines()): lineno += 1 - line = line.strip("\n\r") + line = line.strip('\n\r') empty_the_buffer = True if lineno in excluded: template = TEMPLATE_LOC_EXCLUDED @@ -375,7 +375,7 @@ class CoverStats(object): def serve(path=localFile, port=8080, root=None): if coverage is None: - raise ImportError("The coverage module could not be imported.") + raise ImportError('The coverage module could not be imported.') from coverage import coverage cov = coverage(data_file=path) cov.load() @@ -383,9 +383,9 @@ def serve(path=localFile, port=8080, root=None): import cherrypy cherrypy.config.update({'server.socket_port': int(port), 'server.thread_pool': 10, - 'environment': "production", + 'environment': 'production', }) cherrypy.quickstart(CoverStats(cov, root)) -if __name__ == "__main__": +if __name__ == '__main__': serve(*tuple(sys.argv[1:])) diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index ff21a7f8..42392497 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -33,7 +33,7 @@ def validate_etags(autotags=False, debug=False): response = cherrypy.serving.response # Guard against being run twice. - if hasattr(response, "ETag"): + if hasattr(response, 'ETag'): return status, reason, msg = _httputil.valid_status(response.status) @@ -72,24 +72,24 @@ def validate_etags(autotags=False, debug=False): if debug: cherrypy.log('If-Match conditions: %s' % repr(conditions), 'TOOLS.ETAGS') - if conditions and not (conditions == ["*"] or etag in conditions): - raise cherrypy.HTTPError(412, "If-Match failed: ETag %r did " - "not match %r" % (etag, conditions)) + if conditions and not (conditions == ['*'] or etag in conditions): + raise cherrypy.HTTPError(412, 'If-Match failed: ETag %r did ' + 'not match %r' % (etag, conditions)) conditions = request.headers.elements('If-None-Match') or [] conditions = [str(x) for x in conditions] if debug: cherrypy.log('If-None-Match conditions: %s' % repr(conditions), 'TOOLS.ETAGS') - if conditions == ["*"] or etag in conditions: + if conditions == ['*'] or etag in conditions: if debug: cherrypy.log('request.method: %s' % request.method, 'TOOLS.ETAGS') - if request.method in ("GET", "HEAD"): + if request.method in ('GET', 'HEAD'): raise cherrypy.HTTPRedirect([], 304) else: - raise cherrypy.HTTPError(412, "If-None-Match failed: ETag %r " - "matched %r" % (etag, conditions)) + raise cherrypy.HTTPError(412, 'If-None-Match failed: ETag %r ' + 'matched %r' % (etag, conditions)) def validate_since(): @@ -113,7 +113,7 @@ def validate_since(): since = request.headers.get('If-Modified-Since') if since and since == lastmod: if (status >= 200 and status <= 299) or status == 304: - if request.method in ("GET", "HEAD"): + if request.method in ('GET', 'HEAD'): raise cherrypy.HTTPRedirect([], 304) else: raise cherrypy.HTTPError(412) @@ -186,7 +186,7 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For', # This is for lighttpd/pound/Mongrel's 'X-Forwarded-Proto: https' scheme = s if not scheme: - scheme = request.base[:request.base.find("://")] + scheme = request.base[:request.base.find('://')] if local: lbase = request.headers.get(local, None) @@ -200,9 +200,9 @@ def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For', if port != 80: base += ':%s' % port - if base.find("://") == -1: + if base.find('://') == -1: # add http:// or https:// if needed - base = scheme + "://" + base + base = scheme + '://' + base request.base = base @@ -285,7 +285,7 @@ class SessionAuth(object): """Assert that the user is logged in.""" - session_key = "username" + session_key = 'username' debug = False def check_username_and_password(self, username, password): @@ -317,7 +317,7 @@ Message: %(error_msg)s <br /> <input type="submit" /> </form> -</body></html>""") % vars()).encode("utf-8") +</body></html>""") % vars()).encode('utf-8') def do_login(self, username, password, from_page='..', **kwargs): """Login. May raise redirect, or return True if request handled.""" @@ -326,15 +326,15 @@ Message: %(error_msg)s if error_msg: body = self.login_screen(from_page, username, error_msg) response.body = body - if "Content-Length" in response.headers: + if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. - del response.headers["Content-Length"] + del response.headers['Content-Length'] return True else: cherrypy.serving.request.login = username cherrypy.session[self.session_key] = username self.on_login(username) - raise cherrypy.HTTPRedirect(from_page or "/") + raise cherrypy.HTTPRedirect(from_page or '/') def do_logout(self, from_page='..', **kwargs): """Logout. May raise redirect, or return True if request handled.""" @@ -364,9 +364,9 @@ Message: %(error_msg)s locals(), ) response.body = self.login_screen(url) - if "Content-Length" in response.headers: + if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. - del response.headers["Content-Length"] + del response.headers['Content-Length'] return True self._debug_message('Setting request.login to %(username)r', locals()) request.login = username @@ -388,14 +388,14 @@ Message: %(error_msg)s return True elif path.endswith('do_login'): if request.method != 'POST': - response.headers['Allow'] = "POST" + response.headers['Allow'] = 'POST' self._debug_message('do_login requires POST') raise cherrypy.HTTPError(405) self._debug_message('routing %(path)r to do_login', locals()) return self.do_login(**request.params) elif path.endswith('do_logout'): if request.method != 'POST': - response.headers['Allow'] = "POST" + response.headers['Allow'] = 'POST' raise cherrypy.HTTPError(405) self._debug_message('routing %(path)r to do_logout', locals()) return self.do_logout(**request.params) @@ -414,19 +414,19 @@ session_auth.__doc__ = """Session authentication hook. Any attribute of the SessionAuth class may be overridden via a keyword arg to this function: -""" + "\n".join(["%s: %s" % (k, type(getattr(SessionAuth, k)).__name__) - for k in dir(SessionAuth) if not k.startswith("__")]) +""" + '\n'.join(['%s: %s' % (k, type(getattr(SessionAuth, k)).__name__) + for k in dir(SessionAuth) if not k.startswith('__')]) def log_traceback(severity=logging.ERROR, debug=False): """Write the last error's traceback to the cherrypy error log.""" - cherrypy.log("", "HTTP", severity=severity, traceback=True) + cherrypy.log('', 'HTTP', severity=severity, traceback=True) def log_request_headers(debug=False): """Write request headers to the cherrypy error log.""" - h = [" %s: %s" % (k, v) for k, v in cherrypy.serving.request.header_list] - cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), "HTTP") + h = [' %s: %s' % (k, v) for k, v in cherrypy.serving.request.header_list] + cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), 'HTTP') def log_hooks(debug=False): @@ -442,13 +442,13 @@ def log_hooks(debug=False): points.append(k) for k in points: - msg.append(" %s:" % k) + msg.append(' %s:' % k) v = request.hooks.get(k, []) v.sort() for h in v: - msg.append(" %r" % h) + msg.append(' %r' % h) cherrypy.log('\nRequest Hooks for ' + cherrypy.url() + - ':\n' + '\n'.join(msg), "HTTP") + ':\n' + '\n'.join(msg), 'HTTP') def redirect(url='', internal=True, debug=False): @@ -549,12 +549,12 @@ def accept(media=None, debug=False): # Note that 'ranges' is sorted in order of preference for element in ranges: if element.qvalue > 0: - if element.value == "*/*": + if element.value == '*/*': # Matches any type or subtype if debug: cherrypy.log('Match due to */*', 'TOOLS.ACCEPT') return media[0] - elif element.value.endswith("/*"): + elif element.value.endswith('/*'): # Matches any subtype mtype = element.value[:-1] # Keep the slash for m in media: @@ -574,11 +574,11 @@ def accept(media=None, debug=False): # No suitable media-range found. ah = request.headers.get('Accept') if ah is None: - msg = "Your client did not send an Accept header." + msg = 'Your client did not send an Accept header.' else: - msg = "Your client sent this Accept header: %s." % ah - msg += (" But this resource only emits these media types: %s." % - ", ".join(media)) + msg = 'Your client sent this Accept header: %s.' % ah + msg += (' But this resource only emits these media types: %s.' % + ', '.join(media)) raise cherrypy.HTTPError(406, msg) diff --git a/cherrypy/lib/encoding.py b/cherrypy/lib/encoding.py index e1179415..dc93d990 100644 --- a/cherrypy/lib/encoding.py +++ b/cherrypy/lib/encoding.py @@ -66,7 +66,7 @@ class UTF8StreamEncoder: class ResponseEncoder: default_encoding = 'utf-8' - failmsg = "Response body could not be encoded with %r." + failmsg = 'Response body could not be encoded with %r.' encoding = None errors = 'strict' text_only = True @@ -131,7 +131,7 @@ class ResponseEncoder: encoder = self.encode_stream else: encoder = self.encode_string - if "Content-Length" in response.headers: + if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. # Encoded strings may be of different lengths from their # unicode equivalents, and even from each other. For example: @@ -142,7 +142,7 @@ class ResponseEncoder: # 6 # >>> len(t.encode("utf7")) # 8 - del response.headers["Content-Length"] + del response.headers['Content-Length'] # Parse the Accept-Charset request header, and try to provide one # of the requested charsets (in order of user preference). @@ -157,7 +157,7 @@ class ResponseEncoder: if self.debug: cherrypy.log('Specified encoding %r' % encoding, 'TOOLS.ENCODE') - if (not charsets) or "*" in charsets or encoding in charsets: + if (not charsets) or '*' in charsets or encoding in charsets: if self.debug: cherrypy.log('Attempting encoding %r' % encoding, 'TOOLS.ENCODE') @@ -177,7 +177,7 @@ class ResponseEncoder: else: for element in encs: if element.qvalue > 0: - if element.value == "*": + if element.value == '*': # Matches any charset. Try our default. if self.debug: cherrypy.log('Attempting default encoding due ' @@ -192,7 +192,7 @@ class ResponseEncoder: if encoder(encoding): return encoding - if "*" not in charsets: + if '*' not in charsets: # If no "*" is present in an Accept-Charset field, then all # character sets not explicitly mentioned get a quality # value of 0, except for ISO-8859-1, which gets a quality @@ -208,11 +208,11 @@ class ResponseEncoder: # No suitable encoding found. ac = request.headers.get('Accept-Charset') if ac is None: - msg = "Your client did not send an Accept-Charset header." + msg = 'Your client did not send an Accept-Charset header.' else: - msg = "Your client sent this Accept-Charset header: %s." % ac - _charsets = ", ".join(sorted(self.attempted_charsets)) - msg += " We tried these charsets: %s." % (_charsets,) + msg = 'Your client sent this Accept-Charset header: %s.' % ac + _charsets = ', '.join(sorted(self.attempted_charsets)) + msg += ' We tried these charsets: %s.' % (_charsets,) raise cherrypy.HTTPError(406, msg) def __call__(self, *args, **kwargs): @@ -233,14 +233,14 @@ class ResponseEncoder: elif self.body is None: self.body = [] - ct = response.headers.elements("Content-Type") + ct = response.headers.elements('Content-Type') if self.debug: cherrypy.log('Content-Type: %r' % [str(h) for h in ct], 'TOOLS.ENCODE') if ct and self.add_charset: ct = ct[0] if self.text_only: - if ct.value.lower().startswith("text/"): + if ct.value.lower().startswith('text/'): if self.debug: cherrypy.log( 'Content-Type %s starts with "text/"' % ct, @@ -264,7 +264,7 @@ class ResponseEncoder: if self.debug: cherrypy.log('Setting Content-Type %s' % ct, 'TOOLS.ENCODE') - response.headers["Content-Type"] = str(ct) + response.headers['Content-Type'] = str(ct) return self.body @@ -280,11 +280,11 @@ def compress(body, compress_level): yield ntob('\x08') # CM: compression method yield ntob('\x00') # FLG: none set # MTIME: 4 bytes - yield struct.pack("<L", int(time.time()) & int('FFFFFFFF', 16)) + yield struct.pack('<L', int(time.time()) & int('FFFFFFFF', 16)) yield ntob('\x02') # XFL: max compression, slowest algo yield ntob('\xff') # OS: unknown - crc = zlib.crc32(ntob("")) + crc = zlib.crc32(ntob('')) size = 0 zobj = zlib.compressobj(compress_level, zlib.DEFLATED, -zlib.MAX_WBITS, @@ -296,9 +296,9 @@ def compress(body, compress_level): yield zobj.flush() # CRC32: 4 bytes - yield struct.pack("<L", crc & int('FFFFFFFF', 16)) + yield struct.pack('<L', crc & int('FFFFFFFF', 16)) # ISIZE: 4 bytes - yield struct.pack("<L", size & int('FFFFFFFF', 16)) + yield struct.pack('<L', size & int('FFFFFFFF', 16)) def decompress(body): @@ -335,7 +335,7 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'], request = cherrypy.serving.request response = cherrypy.serving.response - set_vary_header(response, "Accept-Encoding") + set_vary_header(response, 'Accept-Encoding') if not response.body: # Response body is empty (might be a 304 for instance) @@ -345,7 +345,7 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'], # If returning cached content (which should already have been gzipped), # don't re-zip. - if getattr(request, "cached", False): + if getattr(request, 'cached', False): if debug: cherrypy.log('Not gzipping cached response', context='TOOLS.GZIP') return @@ -413,12 +413,12 @@ def gzip(compress_level=5, mime_types=['text/html', 'text/plain'], # Return a generator that compresses the page response.headers['Content-Encoding'] = 'gzip' response.body = compress(response.body, compress_level) - if "Content-Length" in response.headers: + if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. - del response.headers["Content-Length"] + del response.headers['Content-Length'] return if debug: cherrypy.log('No acceptable encoding found.', context='GZIP') - cherrypy.HTTPError(406, "identity, gzip").set_response() + cherrypy.HTTPError(406, 'identity, gzip').set_response() diff --git a/cherrypy/lib/gctools.py b/cherrypy/lib/gctools.py index f8b8025e..f1ab2fec 100644 --- a/cherrypy/lib/gctools.py +++ b/cherrypy/lib/gctools.py @@ -35,7 +35,7 @@ class ReferrerTree(object): refs = gc.get_referrers(obj) self.ignore.append(refs) if len(refs) > self.maxparents: - return [("[%s referrers]" % len(refs), [])] + return [('[%s referrers]' % len(refs), [])] try: ascendcode = self.ascend.__code__ @@ -71,20 +71,20 @@ class ReferrerTree(object): return self.peek(repr(obj)) if isinstance(obj, dict): - return "{" + ", ".join(["%s: %s" % (self._format(k, descend=False), + return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False), self._format(v, descend=False)) - for k, v in obj.items()]) + "}" + for k, v in obj.items()]) + '}' elif isinstance(obj, list): - return "[" + ", ".join([self._format(item, descend=False) - for item in obj]) + "]" + return '[' + ', '.join([self._format(item, descend=False) + for item in obj]) + ']' elif isinstance(obj, tuple): - return "(" + ", ".join([self._format(item, descend=False) - for item in obj]) + ")" + return '(' + ', '.join([self._format(item, descend=False) + for item in obj]) + ')' r = self.peek(repr(obj)) if isinstance(obj, (str, int, float)): return r - return "%s: %s" % (type(obj), r) + return '%s: %s' % (type(obj), r) def format(self, tree): """Return a list of string reprs from a nested list of referrers.""" @@ -92,7 +92,7 @@ class ReferrerTree(object): def ascend(branch, depth=1): for parent, grandparents in branch: - output.append((" " * depth) + self._format(parent)) + output.append((' ' * depth) + self._format(parent)) if grandparents: ascend(grandparents, depth + 1) ascend(tree) @@ -119,14 +119,14 @@ request_counter.subscribe() def get_context(obj): if isinstance(obj, _cprequest.Request): - return "path=%s;stage=%s" % (obj.path_info, obj.stage) + return 'path=%s;stage=%s' % (obj.path_info, obj.stage) elif isinstance(obj, _cprequest.Response): - return "status=%s" % obj.status + return 'status=%s' % obj.status elif isinstance(obj, _cpwsgi.AppResponse): - return "PATH_INFO=%s" % obj.environ.get('PATH_INFO', '') - elif hasattr(obj, "tb_lineno"): - return "tb_lineno=%s" % obj.tb_lineno - return "" + return 'PATH_INFO=%s' % obj.environ.get('PATH_INFO', '') + elif hasattr(obj, 'tb_lineno'): + return 'tb_lineno=%s' % obj.tb_lineno + return '' class GCRoot(object): @@ -135,27 +135,27 @@ class GCRoot(object): classes = [ (_cprequest.Request, 2, 2, - "Should be 1 in this request thread and 1 in the main thread."), + 'Should be 1 in this request thread and 1 in the main thread.'), (_cprequest.Response, 2, 2, - "Should be 1 in this request thread and 1 in the main thread."), + 'Should be 1 in this request thread and 1 in the main thread.'), (_cpwsgi.AppResponse, 1, 1, - "Should be 1 in this request thread only."), + 'Should be 1 in this request thread only.'), ] @cherrypy.expose def index(self): - return "Hello, world!" + return 'Hello, world!' @cherrypy.expose def stats(self): - output = ["Statistics:"] + output = ['Statistics:'] for trial in range(10): if request_counter.count > 0: break time.sleep(0.5) else: - output.append("\nNot all requests closed properly.") + output.append('\nNot all requests closed properly.') # gc_collect isn't perfectly synchronous, because it may # break reference cycles that then take time to fully @@ -173,11 +173,11 @@ class GCRoot(object): for x in gc.garbage: trash[type(x)] = trash.get(type(x), 0) + 1 if trash: - output.insert(0, "\n%s unreachable objects:" % unreachable) + output.insert(0, '\n%s unreachable objects:' % unreachable) trash = [(v, k) for k, v in trash.items()] trash.sort() for pair in trash: - output.append(" " + repr(pair)) + output.append(' ' + repr(pair)) # Check declared classes to verify uncollected instances. # These don't have to be part of a cycle; they can be @@ -193,24 +193,24 @@ class GCRoot(object): if lenobj < minobj or lenobj > maxobj: if minobj == maxobj: output.append( - "\nExpected %s %r references, got %s." % + '\nExpected %s %r references, got %s.' % (minobj, cls, lenobj)) else: output.append( - "\nExpected %s to %s %r references, got %s." % + '\nExpected %s to %s %r references, got %s.' % (minobj, maxobj, cls, lenobj)) for obj in objs: if objgraph is not None: ig = [id(objs), id(inspect.currentframe())] - fname = "graph_%s_%s.png" % (cls.__name__, id(obj)) + fname = 'graph_%s_%s.png' % (cls.__name__, id(obj)) objgraph.show_backrefs( obj, extra_ignore=ig, max_depth=4, too_many=20, filename=fname, extra_info=get_context) - output.append("\nReferrers for %s (refcount=%s):" % + output.append('\nReferrers for %s (refcount=%s):' % (repr(obj), sys.getrefcount(obj))) t = ReferrerTree(ignore=[objs], maxdepth=3) tree = t.ascend(obj) output.extend(t.format(tree)) - return "\n".join(output) + return '\n'.join(output) diff --git a/cherrypy/lib/httpauth.py b/cherrypy/lib/httpauth.py index 87bdc04b..55dd2f89 100644 --- a/cherrypy/lib/httpauth.py +++ b/cherrypy/lib/httpauth.py @@ -31,7 +31,7 @@ from cherrypy._cpcompat import ( __version__ = 1, 0, 1 -__author__ = "Tiago Cogumbreiro <cogumbreiro@users.sf.net>" +__author__ = 'Tiago Cogumbreiro <cogumbreiro@users.sf.net>' __credits__ = """ Peter van Kampen for its recipe which implement most of Digest authentication: @@ -66,16 +66,16 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ -__all__ = ("digestAuth", "basicAuth", "doAuth", "checkResponse", - "parseAuthorization", "SUPPORTED_ALGORITHM", "md5SessionKey", - "calculateNonce", "SUPPORTED_QOP") +__all__ = ('digestAuth', 'basicAuth', 'doAuth', 'checkResponse', + 'parseAuthorization', 'SUPPORTED_ALGORITHM', 'md5SessionKey', + 'calculateNonce', 'SUPPORTED_QOP') ########################################################################## -MD5 = "MD5" -MD5_SESS = "MD5-sess" -AUTH = "auth" -AUTH_INT = "auth-int" +MD5 = 'MD5' +MD5_SESS = 'MD5-sess' +AUTH = 'auth' +AUTH_INT = 'auth-int' SUPPORTED_ALGORITHM = (MD5, MD5_SESS) SUPPORTED_QOP = (AUTH, AUTH_INT) @@ -100,10 +100,10 @@ def calculateNonce(realm, algorithm=MD5): try: encoder = DIGEST_AUTH_ENCODERS[algorithm] except KeyError: - raise NotImplementedError("The chosen algorithm (%s) does not have " - "an implementation yet" % algorithm) + raise NotImplementedError('The chosen algorithm (%s) does not have ' + 'an implementation yet' % algorithm) - return encoder("%d:%s" % (time.time(), realm)) + return encoder('%d:%s' % (time.time(), realm)) def digestAuth(realm, algorithm=MD5, nonce=None, qop=AUTH): @@ -134,7 +134,7 @@ def doAuth(realm): This should be set in the HTTP header under the key 'WWW-Authenticate'.""" - return digestAuth(realm) + " " + basicAuth(realm) + return digestAuth(realm) + ' ' + basicAuth(realm) ########################################################################## @@ -148,31 +148,31 @@ def _parseDigestAuthorization(auth_params): # Now validate the params # Check for required parameters - required = ["username", "realm", "nonce", "uri", "response"] + required = ['username', 'realm', 'nonce', 'uri', 'response'] for k in required: if k not in params: return None # If qop is sent then cnonce and nc MUST be present - if "qop" in params and not ("cnonce" in params - and "nc" in params): + if 'qop' in params and not ('cnonce' in params + and 'nc' in params): return None # If qop is not sent, neither cnonce nor nc can be present - if ("cnonce" in params or "nc" in params) and \ - "qop" not in params: + if ('cnonce' in params or 'nc' in params) and \ + 'qop' not in params: return None return params def _parseBasicAuthorization(auth_params): - username, password = base64_decode(auth_params).split(":", 1) - return {"username": username, "password": password} + username, password = base64_decode(auth_params).split(':', 1) + return {'username': username, 'password': password} AUTH_SCHEMES = { - "basic": _parseBasicAuthorization, - "digest": _parseDigestAuthorization, + 'basic': _parseBasicAuthorization, + 'digest': _parseDigestAuthorization, } @@ -183,7 +183,7 @@ def parseAuthorization(credentials): global AUTH_SCHEMES - auth_scheme, auth_params = credentials.split(" ", 1) + auth_scheme, auth_params = credentials.split(' ', 1) auth_scheme = auth_scheme.lower() parser = AUTH_SCHEMES[auth_scheme] @@ -192,8 +192,8 @@ def parseAuthorization(credentials): if params is None: return - assert "auth_scheme" not in params - params["auth_scheme"] = auth_scheme + assert 'auth_scheme' not in params + params['auth_scheme'] = auth_scheme return params @@ -219,50 +219,50 @@ def md5SessionKey(params, password): specification. """ - keys = ("username", "realm", "nonce", "cnonce") + keys = ('username', 'realm', 'nonce', 'cnonce') params_copy = {} for key in keys: params_copy[key] = params[key] - params_copy["algorithm"] = MD5_SESS + params_copy['algorithm'] = MD5_SESS return _A1(params_copy, password) def _A1(params, password): - algorithm = params.get("algorithm", MD5) + algorithm = params.get('algorithm', MD5) H = DIGEST_AUTH_ENCODERS[algorithm] if algorithm == MD5: # If the "algorithm" directive's value is "MD5" or is # unspecified, then A1 is: # A1 = unq(username-value) ":" unq(realm-value) ":" passwd - return "%s:%s:%s" % (params["username"], params["realm"], password) + return '%s:%s:%s' % (params['username'], params['realm'], password) elif algorithm == MD5_SESS: # This is A1 if qop is set # A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd ) # ":" unq(nonce-value) ":" unq(cnonce-value) - h_a1 = H("%s:%s:%s" % (params["username"], params["realm"], password)) - return "%s:%s:%s" % (h_a1, params["nonce"], params["cnonce"]) + h_a1 = H('%s:%s:%s' % (params['username'], params['realm'], password)) + return '%s:%s:%s' % (h_a1, params['nonce'], params['cnonce']) def _A2(params, method, kwargs): # If the "qop" directive's value is "auth" or is unspecified, then A2 is: # A2 = Method ":" digest-uri-value - qop = params.get("qop", "auth") - if qop == "auth": - return method + ":" + params["uri"] - elif qop == "auth-int": + qop = params.get('qop', 'auth') + if qop == 'auth': + return method + ':' + params['uri'] + elif qop == 'auth-int': # If the "qop" value is "auth-int", then A2 is: # A2 = Method ":" digest-uri-value ":" H(entity-body) - entity_body = kwargs.get("entity_body", "") - H = kwargs["H"] + entity_body = kwargs.get('entity_body', '') + H = kwargs['H'] - return "%s:%s:%s" % ( + return '%s:%s:%s' % ( method, - params["uri"], + params['uri'], H(entity_body) ) @@ -270,19 +270,19 @@ def _A2(params, method, kwargs): raise NotImplementedError("The 'qop' method is unknown: %s" % qop) -def _computeDigestResponse(auth_map, password, method="GET", A1=None, +def _computeDigestResponse(auth_map, password, method='GET', A1=None, **kwargs): """ Generates a response respecting the algorithm defined in RFC 2617 """ params = auth_map - algorithm = params.get("algorithm", MD5) + algorithm = params.get('algorithm', MD5) H = DIGEST_AUTH_ENCODERS[algorithm] - KD = lambda secret, data: H(secret + ":" + data) + KD = lambda secret, data: H(secret + ':' + data) - qop = params.get("qop", None) + qop = params.get('qop', None) H_A2 = H(_A2(params, method, kwargs)) @@ -291,7 +291,7 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None, else: H_A1 = H(_A1(params, password)) - if qop in ("auth", "auth-int"): + if qop in ('auth', 'auth-int'): # If the "qop" value is "auth" or "auth-int": # request-digest = <"> < KD ( H(A1), unq(nonce-value) # ":" nc-value @@ -299,11 +299,11 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None, # ":" unq(qop-value) # ":" H(A2) # ) <"> - request = "%s:%s:%s:%s:%s" % ( - params["nonce"], - params["nc"], - params["cnonce"], - params["qop"], + request = '%s:%s:%s:%s:%s' % ( + params['nonce'], + params['nc'], + params['cnonce'], + params['qop'], H_A2, ) elif qop is None: @@ -311,12 +311,12 @@ def _computeDigestResponse(auth_map, password, method="GET", A1=None, # for compatibility with RFC 2069): # request-digest = # <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> - request = "%s:%s" % (params["nonce"], H_A2) + request = '%s:%s' % (params['nonce'], H_A2) return KD(H_A1, request) -def _checkDigestResponse(auth_map, password, method="GET", A1=None, **kwargs): +def _checkDigestResponse(auth_map, password, method='GET', A1=None, **kwargs): """This function is used to verify the response given by the client when he tries to authenticate. Optional arguments: @@ -334,7 +334,7 @@ def _checkDigestResponse(auth_map, password, method="GET", A1=None, **kwargs): response = _computeDigestResponse( auth_map, password, method, A1, **kwargs) - return response == auth_map["response"] + return response == auth_map['response'] def _checkBasicResponse(auth_map, password, method='GET', encrypt=None, @@ -344,19 +344,19 @@ def _checkBasicResponse(auth_map, password, method='GET', encrypt=None, pass_through = lambda password, username=None: password encrypt = encrypt or pass_through try: - candidate = encrypt(auth_map["password"], auth_map["username"]) + candidate = encrypt(auth_map['password'], auth_map['username']) except TypeError: # if encrypt only takes one parameter, it's the password - candidate = encrypt(auth_map["password"]) + candidate = encrypt(auth_map['password']) return candidate == password AUTH_RESPONSES = { - "basic": _checkBasicResponse, - "digest": _checkDigestResponse, + 'basic': _checkBasicResponse, + 'digest': _checkDigestResponse, } -def checkResponse(auth_map, password, method="GET", encrypt=None, **kwargs): +def checkResponse(auth_map, password, method='GET', encrypt=None, **kwargs): """'checkResponse' compares the auth_map with the password and optionally other arguments that each implementation might need. @@ -373,6 +373,6 @@ def checkResponse(auth_map, password, method="GET", encrypt=None, **kwargs): The 'A1' argument is only used in MD5_SESS algorithm based responses. Check md5SessionKey() for more info. """ - checker = AUTH_RESPONSES[auth_map["auth_scheme"]] + checker = AUTH_RESPONSES[auth_map['auth_scheme']] return checker(auth_map, password, method=method, encrypt=encrypt, **kwargs) diff --git a/cherrypy/lib/httputil.py b/cherrypy/lib/httputil.py index 4c2e52a7..105f9a38 100644 --- a/cherrypy/lib/httputil.py +++ b/cherrypy/lib/httputil.py @@ -45,11 +45,11 @@ def urljoin(*atoms): This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank. """ - url = "/".join([x for x in atoms if x]) - while "//" in url: - url = url.replace("//", "/") + url = '/'.join([x for x in atoms if x]) + while '//' in url: + url = url.replace('//', '/') # Special-case the final url of "", and return "/" instead. - return url or "/" + return url or '/' def urljoin_bytes(*atoms): @@ -58,11 +58,11 @@ def urljoin_bytes(*atoms): This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank. """ - url = ntob("/").join([x for x in atoms if x]) - while ntob("//") in url: - url = url.replace(ntob("//"), ntob("/")) + url = ntob('/').join([x for x in atoms if x]) + while ntob('//') in url: + url = url.replace(ntob('//'), ntob('/')) # Special-case the final url of "", and return "/" instead. - return url or ntob("/") + return url or ntob('/') def protocol_from_http(protocol_str): @@ -85,9 +85,9 @@ def get_ranges(headervalue, content_length): return None result = [] - bytesunit, byteranges = headervalue.split("=", 1) - for brange in byteranges.split(","): - start, stop = [x.strip() for x in brange.split("-", 1)] + bytesunit, byteranges = headervalue.split('=', 1) + for brange in byteranges.split(','): + start, stop = [x.strip() for x in brange.split('-', 1)] if start: if not stop: stop = content_length - 1 @@ -145,8 +145,8 @@ class HeaderElement(object): return self.value < other.value def __str__(self): - p = [";%s=%s" % (k, v) for k, v in iteritems(self.params)] - return str("%s%s" % (self.value, "".join(p))) + p = [';%s=%s' % (k, v) for k, v in iteritems(self.params)] + return str('%s%s' % (self.value, ''.join(p))) def __bytes__(self): return ntob(self.__str__()) @@ -195,13 +195,13 @@ class AcceptElement(HeaderElement): media_type, params = cls.parse(media_range) if qvalue is not None: - params["q"] = qvalue + params['q'] = qvalue return cls(media_type, params) @property def qvalue(self): - "The qvalue, or priority, of this value." - val = self.params.get("q", "1") + 'The qvalue, or priority, of this value.' + val = self.params.get('q', '1') if isinstance(val, HeaderElement): val = val.value return float(val) @@ -227,7 +227,7 @@ def header_elements(fieldname, fieldvalue): result = [] for element in RE_HEADER_SPLIT.split(fieldvalue): - if fieldname.startswith("Accept") or fieldname == 'TE': + if fieldname.startswith('Accept') or fieldname == 'TE': hv = AcceptElement.from_str(element) else: hv = HeaderElement.from_str(element) @@ -239,7 +239,7 @@ def header_elements(fieldname, fieldvalue): def decode_TEXT(value): r"""Decode :rfc:`2047` TEXT (e.g. "=?utf-8?q?f=C3=BCr?=" -> "f\xfcr").""" atoms = decode_header(value) - decodedvalue = "" + decodedvalue = '' for atom, charset in atoms: if charset is not None: atom = atom.decode(charset) @@ -260,7 +260,7 @@ def valid_status(status): status = 200 status = str(status) - parts = status.split(" ", 1) + parts = status.split(' ', 1) if len(parts) == 1: # No reason supplied. code, = parts @@ -272,16 +272,16 @@ def valid_status(status): try: code = int(code) except ValueError: - raise ValueError("Illegal response status from server " - "(%s is non-numeric)." % repr(code)) + raise ValueError('Illegal response status from server ' + '(%s is non-numeric).' % repr(code)) if code < 100 or code > 599: - raise ValueError("Illegal response status from server " - "(%s is out of range)." % repr(code)) + raise ValueError('Illegal response status from server ' + '(%s is out of range).' % repr(code)) if code not in response_codes: # code is unknown but not illegal - default_reason, message = "", "" + default_reason, message = '', '' else: default_reason, message = response_codes[code] @@ -322,7 +322,7 @@ def _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'): nv = name_value.split('=', 1) if len(nv) != 2: if strict_parsing: - raise ValueError("bad query field: %r" % (name_value,)) + raise ValueError('bad query field: %r' % (name_value,)) # Handle case of a control-name with no equal sign if keep_blank_values: nv.append('') @@ -340,7 +340,7 @@ def _parse_qs(qs, keep_blank_values=0, strict_parsing=0, encoding='utf-8'): return d -image_map_pattern = re.compile(r"[0-9]+,[0-9]+") +image_map_pattern = re.compile(r'[0-9]+,[0-9]+') def parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'): @@ -353,7 +353,7 @@ def parse_query_string(query_string, keep_blank_values=True, encoding='utf-8'): if image_map_pattern.match(query_string): # Server-side image map. Map the coords to 'x' and 'y' # (like CGI::Request does). - pm = query_string.split(",") + pm = query_string.split(',') pm = {'x': int(pm[0]), 'y': int(pm[1])} else: pm = _parse_qs(query_string, keep_blank_values, encoding=encoding) @@ -434,7 +434,7 @@ class HeaderMap(CaseInsensitiveDict): """ protocol = (1, 1) - encodings = ["ISO-8859-1"] + encodings = ['ISO-8859-1'] # Someday, when http-bis is done, this will probably get dropped # since few servers, clients, or intermediaries do it. But until then, @@ -500,8 +500,8 @@ class HeaderMap(CaseInsensitiveDict): v = b2a_base64(v.encode('utf-8')) return (ntob('=?utf-8?b?') + v.strip(ntob('\n')) + ntob('?=')) - raise ValueError("Could not encode header part %r using " - "any of the encodings %r." % + raise ValueError('Could not encode header part %r using ' + 'any of the encodings %r.' % (v, cls.encodings)) @@ -515,9 +515,9 @@ class Host(object): """ - ip = "0.0.0.0" + ip = '0.0.0.0' port = 80 - name = "unknown.tld" + name = 'unknown.tld' def __init__(self, ip, port, name=None): self.ip = ip @@ -527,4 +527,4 @@ class Host(object): self.name = name def __repr__(self): - return "httputil.Host(%r, %r, %r)" % (self.ip, self.port, self.name) + return 'httputil.Host(%r, %r, %r)' % (self.ip, self.port, self.name) diff --git a/cherrypy/lib/jsontools.py b/cherrypy/lib/jsontools.py index 52f1f622..91ea74e1 100644 --- a/cherrypy/lib/jsontools.py +++ b/cherrypy/lib/jsontools.py @@ -4,7 +4,7 @@ from cherrypy._cpcompat import text_or_bytes, ntou, json_encode, json_decode def json_processor(entity): """Read application/json data into request.json.""" - if not entity.headers.get(ntou("Content-Length"), ntou("")): + if not entity.headers.get(ntou('Content-Length'), ntou('')): raise cherrypy.HTTPError(411) body = entity.fp.read() diff --git a/cherrypy/lib/lockfile.py b/cherrypy/lib/lockfile.py index 4cf7b1b6..632627be 100644 --- a/cherrypy/lib/lockfile.py +++ b/cherrypy/lib/lockfile.py @@ -17,9 +17,9 @@ except ImportError: class LockError(Exception): - "Could not obtain a lock" + 'Could not obtain a lock' - msg = "Unable to lock %r" + msg = 'Unable to lock %r' def __init__(self, path): super(LockError, self).__init__(self.msg % path) @@ -27,9 +27,9 @@ class LockError(Exception): class UnlockError(LockError): - "Could not release a lock" + 'Could not release a lock' - msg = "Unable to unlock %r" + msg = 'Unable to unlock %r' # first, a default, naive locking implementation @@ -82,7 +82,7 @@ class SystemLockFile(object): del self.fp raise - self.fp.write(" %s\n" % os.getpid()) + self.fp.write(' %s\n' % os.getpid()) self.fp.truncate() self.fp.flush() diff --git a/cherrypy/lib/locking.py b/cherrypy/lib/locking.py index 72dda9b3..317fb58c 100644 --- a/cherrypy/lib/locking.py +++ b/cherrypy/lib/locking.py @@ -11,7 +11,7 @@ class Timer(object): A simple timer that will indicate when an expiration time has passed. """ def __init__(self, expiration): - "Create a timer that expires at `expiration` (UTC datetime)" + 'Create a timer that expires at `expiration` (UTC datetime)' self.expiration = expiration @classmethod @@ -26,7 +26,7 @@ class Timer(object): class LockTimeout(Exception): - "An exception when a lock could not be acquired before a timeout period" + 'An exception when a lock could not be acquired before a timeout period' class LockChecker(object): @@ -43,5 +43,5 @@ class LockChecker(object): def expired(self): if self.timer.expired(): raise LockTimeout( - "Timeout acquiring lock for %(session_id)s" % vars(self)) + 'Timeout acquiring lock for %(session_id)s' % vars(self)) return False diff --git a/cherrypy/lib/profiler.py b/cherrypy/lib/profiler.py index adacb6a9..94b87982 100644 --- a/cherrypy/lib/profiler.py +++ b/cherrypy/lib/profiler.py @@ -50,7 +50,7 @@ try: """Make profiler output more readable by adding `__init__` modules' parents """ filename, line, name = func_name - if filename.endswith("__init__.py"): + if filename.endswith('__init__.py'): return os.path.basename(filename[:-12]) + filename[-12:], line, name return os.path.basename(filename), line, name @@ -67,7 +67,7 @@ class Profiler(object): def __init__(self, path=None): if not path: - path = os.path.join(os.path.dirname(__file__), "profile") + path = os.path.join(os.path.dirname(__file__), 'profile') self.path = path if not os.path.exists(path): os.makedirs(path) @@ -76,7 +76,7 @@ class Profiler(object): """Dump profile data into self.path.""" global _count c = _count = _count + 1 - path = os.path.join(self.path, "cp_%04d.prof" % c) + path = os.path.join(self.path, 'cp_%04d.prof' % c) prof = profile.Profile() result = prof.runcall(func, *args, **params) prof.dump_stats(path) @@ -86,7 +86,7 @@ class Profiler(object): """:rtype: list of available profiles. """ return [f for f in os.listdir(self.path) - if f.startswith("cp_") and f.endswith(".prof")] + if f.startswith('cp_') and f.endswith('.prof')] def stats(self, filename, sortby='cumulative'): """:rtype stats(index): output of print_stats() for the given profile. @@ -126,8 +126,8 @@ class Profiler(object): @cherrypy.expose def menu(self): - yield "<h2>Profiling runs</h2>" - yield "<p>Click on one of the runs below to see profiling data.</p>" + yield '<h2>Profiling runs</h2>' + yield '<p>Click on one of the runs below to see profiling data.</p>' runs = self.statfiles() runs.sort() for i in runs: @@ -149,7 +149,7 @@ class ProfileAggregator(Profiler): self.profiler = profile.Profile() def run(self, func, *args, **params): - path = os.path.join(self.path, "cp_%04d.prof" % self.count) + path = os.path.join(self.path, 'cp_%04d.prof' % self.count) result = self.profiler.runcall(func, *args, **params) self.profiler.dump_stats(path) return result @@ -174,11 +174,11 @@ class make_app: """ if profile is None or pstats is None: - msg = ("Your installation of Python does not have a profile " + msg = ('Your installation of Python does not have a profile ' "module. If you're on Debian, try " - "`sudo apt-get install python-profiler`. " - "See http://www.cherrypy.org/wiki/ProfilingOnDebian " - "for details.") + '`sudo apt-get install python-profiler`. ' + 'See http://www.cherrypy.org/wiki/ProfilingOnDebian ' + 'for details.') warnings.warn(msg) self.nextapp = nextapp @@ -199,19 +199,19 @@ class make_app: def serve(path=None, port=8080): if profile is None or pstats is None: - msg = ("Your installation of Python does not have a profile module. " + msg = ('Your installation of Python does not have a profile module. ' "If you're on Debian, try " - "`sudo apt-get install python-profiler`. " - "See http://www.cherrypy.org/wiki/ProfilingOnDebian " - "for details.") + '`sudo apt-get install python-profiler`. ' + 'See http://www.cherrypy.org/wiki/ProfilingOnDebian ' + 'for details.') warnings.warn(msg) cherrypy.config.update({'server.socket_port': int(port), 'server.thread_pool': 10, - 'environment': "production", + 'environment': 'production', }) cherrypy.quickstart(Profiler(path)) -if __name__ == "__main__": +if __name__ == '__main__': serve(*tuple(sys.argv[1:])) diff --git a/cherrypy/lib/reprconf.py b/cherrypy/lib/reprconf.py index b50ee594..25532921 100644 --- a/cherrypy/lib/reprconf.py +++ b/cherrypy/lib/reprconf.py @@ -78,8 +78,8 @@ class NamespaceSet(dict): # Separate the given config into namespaces ns_confs = {} for k in config: - if "." in k: - ns, name = k.split(".", 1) + if '.' in k: + ns, name = k.split('.', 1) bucket = ns_confs.setdefault(ns, {}) bucket[name] = config[k] @@ -90,7 +90,7 @@ class NamespaceSet(dict): # for k, v in ns_confs.get(ns, {}).iteritems(): # callable(k, v) for ns, handler in self.items(): - exit = getattr(handler, "__exit__", None) + exit = getattr(handler, '__exit__', None) if exit: callable = handler.__enter__() no_exc = True @@ -115,7 +115,7 @@ class NamespaceSet(dict): handler(k, v) def __repr__(self): - return "%s.%s(%s)" % (self.__module__, self.__class__.__name__, + return '%s.%s(%s)' % (self.__module__, self.__class__.__name__, dict.__repr__(self)) def __copy__(self): @@ -213,8 +213,8 @@ class Parser(ConfigParser): value = unrepr(value) except Exception: x = sys.exc_info()[1] - msg = ("Config error in section: %r, option: %r, " - "value: %r. Config values must be valid Python." % + msg = ('Config error in section: %r, option: %r, ' + 'value: %r. Config values must be valid Python.' % (section, option, value)) raise ValueError(msg, x.__class__.__name__, x.args) result[section][option] = value @@ -236,7 +236,7 @@ class _Builder2: def build(self, o): m = getattr(self, 'build_' + o.__class__.__name__, None) if m is None: - raise TypeError("unrepr does not recognize %s" % + raise TypeError('unrepr does not recognize %s' % repr(o.__class__.__name__)) return m(o) @@ -249,7 +249,7 @@ class _Builder2: # e.g. IronPython 1.0. return eval(s) - p = compiler.parse("__tempvalue__ = " + s) + p = compiler.parse('__tempvalue__ = ' + s) return p.getChildren()[1].getChildren()[0].getChildren()[1] def build_Subscript(self, o): @@ -322,7 +322,7 @@ class _Builder2: except AttributeError: pass - raise TypeError("unrepr could not resolve the name %s" % repr(name)) + raise TypeError('unrepr could not resolve the name %s' % repr(name)) def build_Add(self, o): left, right = map(self.build, o.getChildren()) @@ -351,7 +351,7 @@ class _Builder3: def build(self, o): m = getattr(self, 'build_' + o.__class__.__name__, None) if m is None: - raise TypeError("unrepr does not recognize %s" % + raise TypeError('unrepr does not recognize %s' % repr(o.__class__.__name__)) return m(o) @@ -364,7 +364,7 @@ class _Builder3: # e.g. IronPython 1.0. return eval(s) - p = ast.parse("__tempvalue__ = " + s) + p = ast.parse('__tempvalue__ = ' + s) return p.body[0].value def build_Subscript(self, o): @@ -392,8 +392,8 @@ class _Builder3: if kw.arg is None: # double asterix `**` rst = self.build(kw.value) if not isinstance(rst, dict): - raise TypeError("Invalid argument for call." - "Must be a mapping object.") + raise TypeError('Invalid argument for call.' + 'Must be a mapping object.') # give preference to the keys set directly from arg=value for k, v in rst.items(): if k not in kwargs: @@ -466,7 +466,7 @@ class _Builder3: except AttributeError: pass - raise TypeError("unrepr could not resolve the name %s" % repr(name)) + raise TypeError('unrepr could not resolve the name %s' % repr(name)) def build_NameConstant(self, o): return o.value @@ -518,7 +518,7 @@ def attributes(full_attribute_name): """Load a module and retrieve an attribute of that module.""" # Parse out the path, module, and attribute - last_dot = full_attribute_name.rfind(".") + last_dot = full_attribute_name.rfind('.') attr_name = full_attribute_name[last_dot + 1:] mod_path = full_attribute_name[:last_dot] diff --git a/cherrypy/lib/sessions.py b/cherrypy/lib/sessions.py index 2f93bf62..e28cbcc1 100644 --- a/cherrypy/lib/sessions.py +++ b/cherrypy/lib/sessions.py @@ -121,10 +121,10 @@ class Session(object): self._id = value for o in self.id_observers: o(value) - id = property(_get_id, _set_id, doc="The current session ID.") + id = property(_get_id, _set_id, doc='The current session ID.') timeout = 60 - "Number of minutes after which to delete session data." + 'Number of minutes after which to delete session data.' locked = False """ @@ -137,16 +137,16 @@ class Session(object): automatically on the first attempt to access session data.""" clean_thread = None - "Class-level Monitor which calls self.clean_up." + 'Class-level Monitor which calls self.clean_up.' clean_freq = 5 - "The poll rate for expired session cleanup in minutes." + 'The poll rate for expired session cleanup in minutes.' originalid = None - "The session id passed by the client. May be missing or unsafe." + 'The session id passed by the client. May be missing or unsafe.' missing = False - "True if the session requested by the client did not exist." + 'True if the session requested by the client did not exist.' regenerated = False """ @@ -154,7 +154,7 @@ class Session(object): internal calls to regenerate the session id.""" debug = False - "If True, log debug information." + 'If True, log debug information.' # --------------------- Session management methods --------------------- # @@ -470,8 +470,8 @@ class FileSession(Session): if isinstance(self.lock_timeout, (int, float)): self.lock_timeout = datetime.timedelta(seconds=self.lock_timeout) if not isinstance(self.lock_timeout, (datetime.timedelta, type(None))): - raise ValueError("Lock timeout must be numeric seconds or " - "a timedelta instance.") + raise ValueError('Lock timeout must be numeric seconds or ' + 'a timedelta instance.') @classmethod def setup(cls, **kwargs): @@ -489,7 +489,7 @@ class FileSession(Session): def _get_file_path(self): f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id) if not os.path.abspath(f).startswith(self.storage_path): - raise cherrypy.HTTPError(400, "Invalid session id in cookie.") + raise cherrypy.HTTPError(400, 'Invalid session id in cookie.') return f def _exists(self): @@ -497,12 +497,12 @@ class FileSession(Session): return os.path.exists(path) def _load(self, path=None): - assert self.locked, ("The session load without being locked. " + assert self.locked, ('The session load without being locked. ' "Check your tools' priority levels.") if path is None: path = self._get_file_path() try: - f = open(path, "rb") + f = open(path, 'rb') try: return pickle.load(f) finally: @@ -510,21 +510,21 @@ class FileSession(Session): except (IOError, EOFError): e = sys.exc_info()[1] if self.debug: - cherrypy.log("Error loading the session pickle: %s" % + cherrypy.log('Error loading the session pickle: %s' % e, 'TOOLS.SESSIONS') return None def _save(self, expiration_time): - assert self.locked, ("The session was saved without being locked. " + assert self.locked, ('The session was saved without being locked. ' "Check your tools' priority levels.") - f = open(self._get_file_path(), "wb") + f = open(self._get_file_path(), 'wb') try: pickle.dump((self._data, expiration_time), f, self.pickle_protocol) finally: f.close() def _delete(self): - assert self.locked, ("The session deletion without being locked. " + assert self.locked, ('The session deletion without being locked. ' "Check your tools' priority levels.") try: os.unlink(self._get_file_path()) @@ -635,7 +635,7 @@ class MemcachedSession(Session): try: if not self.cache.set(self.id, (self._data, expiration_time), td): raise AssertionError( - "Session data for id %r not set." % self.id) + 'Session data for id %r not set.' % self.id) finally: self.mc_lock.release() @@ -664,13 +664,13 @@ class MemcachedSession(Session): def save(): """Save any changed session data.""" - if not hasattr(cherrypy.serving, "session"): + if not hasattr(cherrypy.serving, 'session'): return request = cherrypy.serving.request response = cherrypy.serving.response # Guard against running twice - if hasattr(request, "_sessionsaved"): + if hasattr(request, '_sessionsaved'): return request._sessionsaved = True @@ -689,8 +689,8 @@ save.failsafe = True def close(): """Close the session object for this request.""" - sess = getattr(cherrypy.serving, "session", None) - if getattr(sess, "locked", False): + sess = getattr(cherrypy.serving, 'session', None) + if getattr(sess, 'locked', False): # If the session is still locked we release the lock sess.release_lock() if sess.debug: @@ -762,7 +762,7 @@ def init(storage_type=None, path=None, path_header=None, name='session_id', request = cherrypy.serving.request # Guard against running twice - if hasattr(request, "_session_init_flag"): + if hasattr(request, '_session_init_flag'): return request._session_init_flag = True @@ -774,18 +774,18 @@ def init(storage_type=None, path=None, path_header=None, name='session_id', cherrypy.log('ID obtained from request.cookie: %r' % id, 'TOOLS.SESSIONS') - first_time = not hasattr(cherrypy, "session") + first_time = not hasattr(cherrypy, 'session') if storage_type: if first_time: - msg = "storage_type is deprecated. Supply storage_class instead" + msg = 'storage_type is deprecated. Supply storage_class instead' cherrypy.log(msg) storage_class = storage_type.title() + 'Session' storage_class = globals()[storage_class] # call setup first time only if first_time: - if hasattr(storage_class, "setup"): + if hasattr(storage_class, 'setup'): storage_class.setup(**kwargs) # Create and attach a new Session instance to cherrypy.serving. @@ -802,7 +802,7 @@ def init(storage_type=None, path=None, path_header=None, name='session_id', sess.id_observers.append(update_cookie) # Create cherrypy.session which will proxy to cherrypy.serving.session - if not hasattr(cherrypy, "session"): + if not hasattr(cherrypy, 'session'): cherrypy.session = cherrypy._ThreadLocalProxy('session') if persistent: @@ -870,7 +870,7 @@ def set_response_cookie(path=None, path_header=None, name='session_id', cookie[name]['secure'] = 1 if httponly: if not cookie[name].isReservedKey('httponly'): - raise ValueError("The httponly cookie token is not supported.") + raise ValueError('The httponly cookie token is not supported.') cookie[name]['httponly'] = 1 diff --git a/cherrypy/lib/static.py b/cherrypy/lib/static.py index 6a78fc13..4159c860 100644 --- a/cherrypy/lib/static.py +++ b/cherrypy/lib/static.py @@ -71,7 +71,7 @@ def serve_file(path, content_type=None, disposition=None, name=None, if content_type is None: # Set content-type based on filename extension - ext = "" + ext = '' i = path.rfind('.') if i != -1: ext = path[i:].lower() @@ -86,7 +86,7 @@ def serve_file(path, content_type=None, disposition=None, name=None, if name is None: name = os.path.basename(path) cd = '%s; filename="%s"' % (disposition, name) - response.headers["Content-Disposition"] = cd + response.headers['Content-Disposition'] = cd if debug: cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC') @@ -144,7 +144,7 @@ def serve_fileobj(fileobj, content_type=None, disposition=None, name=None, cd = disposition else: cd = '%s; filename="%s"' % (disposition, name) - response.headers["Content-Disposition"] = cd + response.headers['Content-Disposition'] = cd if debug: cherrypy.log('Content-Disposition: %r' % cd, 'TOOLS.STATIC') @@ -158,12 +158,12 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False): # HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code request = cherrypy.serving.request if request.protocol >= (1, 1): - response.headers["Accept-Ranges"] = "bytes" + response.headers['Accept-Ranges'] = 'bytes' r = httputil.get_ranges(request.headers.get('Range'), content_length) if r == []: - response.headers['Content-Range'] = "bytes */%s" % content_length - message = ("Invalid Range (first-byte-pos greater than " - "Content-Length)") + response.headers['Content-Range'] = 'bytes */%s' % content_length + message = ('Invalid Range (first-byte-pos greater than ' + 'Content-Length)') if debug: cherrypy.log(message, 'TOOLS.STATIC') raise cherrypy.HTTPError(416, message) @@ -179,15 +179,15 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False): cherrypy.log( 'Single part; start: %r, stop: %r' % (start, stop), 'TOOLS.STATIC') - response.status = "206 Partial Content" + response.status = '206 Partial Content' response.headers['Content-Range'] = ( - "bytes %s-%s/%s" % (start, stop - 1, content_length)) + 'bytes %s-%s/%s' % (start, stop - 1, content_length)) response.headers['Content-Length'] = r_len fileobj.seek(start) response.body = file_generator_limited(fileobj, r_len) else: # Return a multipart/byteranges response. - response.status = "206 Partial Content" + response.status = '206 Partial Content' try: # Python 3 from email.generator import _make_boundary as make_boundary @@ -195,15 +195,15 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False): # Python 2 from mimetools import choose_boundary as make_boundary boundary = make_boundary() - ct = "multipart/byteranges; boundary=%s" % boundary + ct = 'multipart/byteranges; boundary=%s' % boundary response.headers['Content-Type'] = ct - if "Content-Length" in response.headers: + if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. - del response.headers["Content-Length"] + del response.headers['Content-Length'] def file_ranges(): # Apache compatibility: - yield ntob("\r\n") + yield ntob('\r\n') for start, stop in r: if debug: @@ -211,23 +211,23 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False): 'Multipart; start: %r, stop: %r' % ( start, stop), 'TOOLS.STATIC') - yield ntob("--" + boundary, 'ascii') - yield ntob("\r\nContent-type: %s" % content_type, + yield ntob('--' + boundary, 'ascii') + yield ntob('\r\nContent-type: %s' % content_type, 'ascii') yield ntob( - "\r\nContent-range: bytes %s-%s/%s\r\n\r\n" % ( + '\r\nContent-range: bytes %s-%s/%s\r\n\r\n' % ( start, stop - 1, content_length), 'ascii') fileobj.seek(start) gen = file_generator_limited(fileobj, stop - start) for chunk in gen: yield chunk - yield ntob("\r\n") + yield ntob('\r\n') # Final boundary - yield ntob("--" + boundary + "--", 'ascii') + yield ntob('--' + boundary + '--', 'ascii') # Apache compatibility: - yield ntob("\r\n") + yield ntob('\r\n') response.body = file_ranges() return response.body else: @@ -244,7 +244,7 @@ def _serve_fileobj(fileobj, content_type, content_length, debug=False): def serve_download(path, name=None): """Serve 'path' as an application/x-download attachment.""" # This is such a common idiom I felt it deserved its own wrapper. - return serve_file(path, "application/x-download", "attachment", name) + return serve_file(path, 'application/x-download', 'attachment', name) def _attempt(filename, content_types, debug=False): @@ -268,7 +268,7 @@ def _attempt(filename, content_types, debug=False): return False -def staticdir(section, dir, root="", match="", content_types=None, index="", +def staticdir(section, dir, root='', match='', content_types=None, index='', debug=False): """Serve a static resource from the given (root +) dir. @@ -306,7 +306,7 @@ def staticdir(section, dir, root="", match="", content_types=None, index="", # If dir is relative, make absolute using "root". if not os.path.isabs(dir): if not root: - msg = "Static dir requires an absolute dir (or root)." + msg = 'Static dir requires an absolute dir (or root).' if debug: cherrypy.log(msg, 'TOOLS.STATICDIR') raise ValueError(msg) @@ -315,10 +315,10 @@ def staticdir(section, dir, root="", match="", content_types=None, index="", # Determine where we are in the object tree relative to 'section' # (where the static tool was defined). if section == 'global': - section = "/" - section = section.rstrip(r"\/") + section = '/' + section = section.rstrip(r'\/') branch = request.path_info[len(section) + 1:] - branch = unquote(branch.lstrip(r"\/")) + branch = unquote(branch.lstrip(r'\/')) # If branch is "", filename will end in a slash filename = os.path.join(dir, branch) @@ -338,11 +338,11 @@ def staticdir(section, dir, root="", match="", content_types=None, index="", if index: handled = _attempt(os.path.join(filename, index), content_types) if handled: - request.is_index = filename[-1] in (r"\/") + request.is_index = filename[-1] in (r'\/') return handled -def staticfile(filename, root=None, match="", content_types=None, debug=False): +def staticfile(filename, root=None, match='', content_types=None, debug=False): """Serve a static resource from the given (root +) filename. match diff --git a/cherrypy/process/plugins.py b/cherrypy/process/plugins.py index 97d559d6..31e7d768 100644 --- a/cherrypy/process/plugins.py +++ b/cherrypy/process/plugins.py @@ -104,8 +104,8 @@ class SignalHandler(object): if sys.platform[:4] == 'java': del self.handlers['SIGUSR1'] self.handlers['SIGUSR2'] = self.bus.graceful - self.bus.log("SIGUSR1 cannot be set on the JVM platform. " - "Using SIGUSR2 instead.") + self.bus.log('SIGUSR1 cannot be set on the JVM platform. ' + 'Using SIGUSR2 instead.') self.handlers['SIGINT'] = self._jython_SIGINT_handler self._previous_handlers = {} @@ -152,19 +152,19 @@ class SignalHandler(object): signame = self.signals[signum] if handler is None: - self.bus.log("Restoring %s handler to SIG_DFL." % signame) + self.bus.log('Restoring %s handler to SIG_DFL.' % signame) handler = _signal.SIG_DFL else: - self.bus.log("Restoring %s handler %r." % (signame, handler)) + self.bus.log('Restoring %s handler %r.' % (signame, handler)) try: our_handler = _signal.signal(signum, handler) if our_handler is None: - self.bus.log("Restored old %s handler %r, but our " - "handler was not registered." % + self.bus.log('Restored old %s handler %r, but our ' + 'handler was not registered.' % (signame, handler), level=30) except ValueError: - self.bus.log("Unable to restore %s handler %r." % + self.bus.log('Unable to restore %s handler %r.' % (signame, handler), level=40, traceback=True) def set_handler(self, signal, listener=None): @@ -179,36 +179,36 @@ class SignalHandler(object): if isinstance(signal, text_or_bytes): signum = getattr(_signal, signal, None) if signum is None: - raise ValueError("No such signal: %r" % signal) + raise ValueError('No such signal: %r' % signal) signame = signal else: try: signame = self.signals[signal] except KeyError: - raise ValueError("No such signal: %r" % signal) + raise ValueError('No such signal: %r' % signal) signum = signal prev = _signal.signal(signum, self._handle_signal) self._previous_handlers[signum] = prev if listener is not None: - self.bus.log("Listening for %s." % signame) + self.bus.log('Listening for %s.' % signame) self.bus.subscribe(signame, listener) def _handle_signal(self, signum=None, frame=None): """Python signal handler (self.set_handler subscribes it for you).""" signame = self.signals[signum] - self.bus.log("Caught signal %s." % signame) + self.bus.log('Caught signal %s.' % signame) self.bus.publish(signame) def handle_SIGHUP(self): """Restart if daemonized, else exit.""" if self._is_daemonized(): - self.bus.log("SIGHUP caught while daemonized. Restarting.") + self.bus.log('SIGHUP caught while daemonized. Restarting.') self.bus.restart() else: # not daemonized (may be foreground or background) - self.bus.log("SIGHUP caught but not daemonized. Exiting.") + self.bus.log('SIGHUP caught but not daemonized. Exiting.') self.bus.exit() @@ -239,14 +239,14 @@ class DropPrivileges(SimplePlugin): def _set_uid(self, val): if val is not None: if pwd is None: - self.bus.log("pwd module not available; ignoring uid.", + self.bus.log('pwd module not available; ignoring uid.', level=30) val = None elif isinstance(val, text_or_bytes): val = pwd.getpwnam(val)[2] self._uid = val uid = property(_get_uid, _set_uid, - doc="The uid under which to run. Availability: Unix.") + doc='The uid under which to run. Availability: Unix.') def _get_gid(self): return self._gid @@ -254,14 +254,14 @@ class DropPrivileges(SimplePlugin): def _set_gid(self, val): if val is not None: if grp is None: - self.bus.log("grp module not available; ignoring gid.", + self.bus.log('grp module not available; ignoring gid.', level=30) val = None elif isinstance(val, text_or_bytes): val = grp.getgrnam(val)[2] self._gid = val gid = property(_get_gid, _set_gid, - doc="The gid under which to run. Availability: Unix.") + doc='The gid under which to run. Availability: Unix.') def _get_umask(self): return self._umask @@ -271,7 +271,7 @@ class DropPrivileges(SimplePlugin): try: os.umask except AttributeError: - self.bus.log("umask function not available; ignoring umask.", + self.bus.log('umask function not available; ignoring umask.', level=30) val = None self._umask = val @@ -393,7 +393,7 @@ class Daemonizer(SimplePlugin): except OSError: # Python raises OSError rather than returning negative numbers. exc = sys.exc_info()[1] - sys.exit("%s: fork #1 failed: (%d) %s\n" + sys.exit('%s: fork #1 failed: (%d) %s\n' % (sys.argv[0], exc.errno, exc.strerror)) os.setsid() @@ -406,15 +406,15 @@ class Daemonizer(SimplePlugin): os._exit(0) # Exit second parent except OSError: exc = sys.exc_info()[1] - sys.exit("%s: fork #2 failed: (%d) %s\n" + sys.exit('%s: fork #2 failed: (%d) %s\n' % (sys.argv[0], exc.errno, exc.strerror)) - os.chdir("/") + os.chdir('/') os.umask(0) - si = open(self.stdin, "r") - so = open(self.stdout, "a+") - se = open(self.stderr, "a+") + si = open(self.stdin, 'r') + so = open(self.stdout, 'a+') + se = open(self.stderr, 'a+') # os.dup2(fd, fd2) will close fd2 if necessary, # so we don't explicitly close stdin/out/err. @@ -442,7 +442,7 @@ class PIDFile(SimplePlugin): if self.finalized: self.bus.log('PID %r already written to %r.' % (pid, self.pidfile)) else: - open(self.pidfile, "wb").write(ntob("%s\n" % pid, 'utf8')) + open(self.pidfile, 'wb').write(ntob('%s\n' % pid, 'utf8')) self.bus.log('PID %r written to %r.' % (pid, self.pidfile)) self.finalized = True start.priority = 70 @@ -481,7 +481,7 @@ class PerpetualTimer(Timer): except Exception: if self.bus: self.bus.log( - "Error in perpetual timer thread function %r." % + 'Error in perpetual timer thread function %r.' % self.function, level=40, traceback=True) # Quit on first error to avoid massive logs. raise @@ -523,7 +523,7 @@ class BackgroundTask(threading.Thread): self.function(*self.args, **self.kwargs) except Exception: if self.bus: - self.bus.log("Error in background task thread function %r." + self.bus.log('Error in background task thread function %r.' % self.function, level=40, traceback=True) # Quit on first error to avoid massive logs. raise @@ -560,24 +560,24 @@ class Monitor(SimplePlugin): bus=self.bus) self.thread.setName(threadname) self.thread.start() - self.bus.log("Started monitor thread %r." % threadname) + self.bus.log('Started monitor thread %r.' % threadname) else: - self.bus.log("Monitor thread %r already started." % threadname) + self.bus.log('Monitor thread %r already started.' % threadname) start.priority = 70 def stop(self): """Stop our callback's background task thread.""" if self.thread is None: - self.bus.log("No thread running for %s." % + self.bus.log('No thread running for %s.' % self.name or self.__class__.__name__) else: if self.thread is not threading.currentThread(): name = self.thread.getName() self.thread.cancel() if not self.thread.daemon: - self.bus.log("Joining %r" % name) + self.bus.log('Joining %r' % name) self.thread.join() - self.bus.log("Stopped thread %r." % name) + self.bus.log('Stopped thread %r.' % name) self.thread = None def graceful(self): @@ -674,10 +674,10 @@ class Autoreloader(Monitor): else: if mtime is None or mtime > oldtime: # The file has been deleted or modified. - self.bus.log("Restarting because %s changed." % + self.bus.log('Restarting because %s changed.' % filename) self.thread.cancel() - self.bus.log("Stopped thread %r." % + self.bus.log('Stopped thread %r.' % self.thread.getName()) self.bus.restart() return diff --git a/cherrypy/process/servers.py b/cherrypy/process/servers.py index 83304efd..7d6ec6c9 100644 --- a/cherrypy/process/servers.py +++ b/cherrypy/process/servers.py @@ -152,19 +152,19 @@ class ServerAdapter(object): def start(self): """Start the HTTP server.""" if self.bind_addr is None: - on_what = "unknown interface (dynamic?)" + on_what = 'unknown interface (dynamic?)' elif isinstance(self.bind_addr, tuple): on_what = self._get_base() else: - on_what = "socket file: %s" % self.bind_addr + on_what = 'socket file: %s' % self.bind_addr if self.running: - self.bus.log("Already serving on %s" % on_what) + self.bus.log('Already serving on %s' % on_what) return self.interrupt = None if not self.httpserver: - raise ValueError("No HTTP server has been created.") + raise ValueError('No HTTP server has been created.') if not os.environ.get('LISTEN_PID', None): # Start the httpserver in a new thread. @@ -173,12 +173,12 @@ class ServerAdapter(object): import threading t = threading.Thread(target=self._start_http_thread) - t.setName("HTTPServer " + t.getName()) + t.setName('HTTPServer ' + t.getName()) t.start() self.wait() self.running = True - self.bus.log("Serving on %s" % on_what) + self.bus.log('Serving on %s' % on_what) start.priority = 75 def _get_base(self): @@ -186,15 +186,15 @@ class ServerAdapter(object): return '' host, port = self.bind_addr if getattr(self.httpserver, 'ssl_adapter', None): - scheme = "https" + scheme = 'https' if port != 443: - host += ":%s" % port + host += ':%s' % port else: - scheme = "http" + scheme = 'http' if port != 80: - host += ":%s" % port + host += ':%s' % port - return "%s://%s" % (scheme, host) + return '%s://%s' % (scheme, host) def _start_http_thread(self): """HTTP servers MUST be running in new threads, so that the @@ -206,24 +206,24 @@ class ServerAdapter(object): try: self.httpserver.start() except KeyboardInterrupt: - self.bus.log("<Ctrl-C> hit: shutting down HTTP server") + self.bus.log('<Ctrl-C> hit: shutting down HTTP server') self.interrupt = sys.exc_info()[1] self.bus.exit() except SystemExit: - self.bus.log("SystemExit raised: shutting down HTTP server") + self.bus.log('SystemExit raised: shutting down HTTP server') self.interrupt = sys.exc_info()[1] self.bus.exit() raise except: self.interrupt = sys.exc_info()[1] - self.bus.log("Error in HTTP server: shutting down", + self.bus.log('Error in HTTP server: shutting down', traceback=True, level=40) self.bus.exit() raise def wait(self): """Wait until the HTTP server is ready to receive requests.""" - while not getattr(self.httpserver, "ready", False): + while not getattr(self.httpserver, 'ready', False): if self.interrupt: raise self.interrupt time.sleep(.1) @@ -245,9 +245,9 @@ class ServerAdapter(object): if isinstance(self.bind_addr, tuple): wait_for_free_port(*self.bind_addr) self.running = False - self.bus.log("HTTP Server %s shut down" % self.httpserver) + self.bus.log('HTTP Server %s shut down' % self.httpserver) else: - self.bus.log("HTTP Server %s already shut down" % self.httpserver) + self.bus.log('HTTP Server %s already shut down' % self.httpserver) stop.priority = 25 def restart(self): @@ -394,10 +394,10 @@ def check_port(host, port, timeout=1.0): except socket.gaierror: if ':' in host: info = [( - socket.AF_INET6, socket.SOCK_STREAM, 0, "", (host, port, 0, 0) + socket.AF_INET6, socket.SOCK_STREAM, 0, '', (host, port, 0, 0) )] else: - info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))] + info = [(socket.AF_INET, socket.SOCK_STREAM, 0, '', (host, port))] for res in info: af, socktype, proto, canonname, sa = res @@ -413,8 +413,8 @@ def check_port(host, port, timeout=1.0): if s: s.close() else: - raise IOError("Port %s is in use on %s; perhaps the previous " - "httpserver did not shut down properly." % + raise IOError('Port %s is in use on %s; perhaps the previous ' + 'httpserver did not shut down properly.' % (repr(port), repr(host))) @@ -440,7 +440,7 @@ def wait_for_free_port(host, port, timeout=None): else: return - raise IOError("Port %r not free on %r" % (port, host)) + raise IOError('Port %r not free on %r' % (port, host)) def wait_for_occupied_port(host, port, timeout=None): @@ -460,11 +460,11 @@ def wait_for_occupied_port(host, port, timeout=None): time.sleep(timeout) if host == client_host(host): - raise IOError("Port %r not bound on %r" % (port, host)) + raise IOError('Port %r not bound on %r' % (port, host)) # On systems where a loopback interface is not available and the # server is bound to all interfaces, it's difficult to determine # whether the server is in fact occupying the port. In this case, # just issue a warning and move on. See issue #1100. - msg = "Unable to verify that the server is bound on %r" % port + msg = 'Unable to verify that the server is bound on %r' % port warnings.warn(msg) diff --git a/cherrypy/process/win32.py b/cherrypy/process/win32.py index 4afd3f14..edaf48b2 100644 --- a/cherrypy/process/win32.py +++ b/cherrypy/process/win32.py @@ -85,7 +85,7 @@ class Win32Bus(wspbus.Bus): return self.events[state] except KeyError: event = win32event.CreateEvent(None, 0, 0, - "WSPBus %s Event (pid=%r)" % + 'WSPBus %s Event (pid=%r)' % (state.name, os.getpid())) self.events[state] = event return event @@ -135,7 +135,7 @@ class _ControlCodes(dict): for key, val in self.items(): if val is obj: return key - raise ValueError("The given object could not be found: %r" % obj) + raise ValueError('The given object could not be found: %r' % obj) control_codes = _ControlCodes({'graceful': 138}) @@ -153,14 +153,14 @@ class PyWebService(win32serviceutil.ServiceFramework): """Python Web Service.""" - _svc_name_ = "Python Web Service" - _svc_display_name_ = "Python Web Service" + _svc_name_ = 'Python Web Service' + _svc_display_name_ = 'Python Web Service' _svc_deps_ = None # sequence of service names on which this depends - _exe_name_ = "pywebsvc" + _exe_name_ = 'pywebsvc' _exe_args_ = None # Default to no arguments # Only exists on Windows 2000 or later, ignored on windows NT - _svc_description_ = "Python Web Service" + _svc_description_ = 'Python Web Service' def SvcDoRun(self): from cherrypy import process diff --git a/cherrypy/process/wspbus.py b/cherrypy/process/wspbus.py index 4186a96e..edd21fdc 100644 --- a/cherrypy/process/wspbus.py +++ b/cherrypy/process/wspbus.py @@ -117,7 +117,7 @@ class _StateEnum(object): name = None def __repr__(self): - return "states.%s" % self.name + return 'states.%s' % self.name def __setattr__(self, key, value): if isinstance(value, self.State): @@ -214,7 +214,7 @@ class Bus(object): # Assume any further messages to 'log' will fail. pass else: - self.log("Error in %r listener %r" % (channel, listener), + self.log('Error in %r listener %r' % (channel, listener), level=40, traceback=True) if exc: raise exc @@ -224,10 +224,10 @@ class Bus(object): """An atexit handler which asserts the Bus is not running.""" if self.state != states.EXITING: warnings.warn( - "The main thread is exiting, but the Bus is in the %r state; " - "shutting it down automatically now. You must either call " - "bus.block() after start(), or call bus.exit() before the " - "main thread exits." % self.state, RuntimeWarning) + 'The main thread is exiting, but the Bus is in the %r state; ' + 'shutting it down automatically now. You must either call ' + 'bus.block() after start(), or call bus.exit() before the ' + 'main thread exits.' % self.state, RuntimeWarning) self.exit() def start(self): @@ -243,7 +243,7 @@ class Bus(object): except (KeyboardInterrupt, SystemExit): raise except: - self.log("Shutting down due to error in start listener:", + self.log('Shutting down due to error in start listener:', level=40, traceback=True) e_info = sys.exc_info()[1] try: @@ -320,7 +320,7 @@ class Bus(object): # It's also good to let them all shut down before allowing # the main thread to call atexit handlers. # See https://github.com/cherrypy/cherrypy/issues/751. - self.log("Waiting for child threads to terminate...") + self.log('Waiting for child threads to terminate...') for t in threading.enumerate(): # Validate the we're not trying to join the MainThread # that will cause a deadlock and the case exist when @@ -332,13 +332,13 @@ class Bus(object): not isinstance(t, threading._MainThread) ): # Note that any dummy (external) threads are always daemonic. - if hasattr(threading.Thread, "daemon"): + if hasattr(threading.Thread, 'daemon'): # Python 2.6+ d = t.daemon else: d = t.isDaemon() if not d: - self.log("Waiting for thread %s." % t.getName()) + self.log('Waiting for thread %s.' % t.getName()) t.join() if self.execv: @@ -415,7 +415,7 @@ class Bus(object): ) if needs_patch: - env["PYTHONPATH"] = path_prefix + existing_path + env['PYTHONPATH'] = path_prefix + existing_path def _set_cloexec(self): """Set the CLOEXEC flag on all open files (except stdin/out/err). @@ -462,10 +462,10 @@ class Bus(object): return t - def log(self, msg="", level=20, traceback=False): + def log(self, msg='', level=20, traceback=False): """Log the given message. Append the last traceback if requested.""" if traceback: - msg += "\n" + "".join(_traceback.format_exception(*sys.exc_info())) + msg += '\n' + ''.join(_traceback.format_exception(*sys.exc_info())) self.publish('log', msg, level) bus = Bus() diff --git a/cherrypy/scaffold/__init__.py b/cherrypy/scaffold/__init__.py index 9bb4502a..a2672743 100644 --- a/cherrypy/scaffold/__init__.py +++ b/cherrypy/scaffold/__init__.py @@ -29,24 +29,24 @@ class Root: or a <a href='%s?n=14'>default</a> path.<br /> Or, just look at the pretty picture:<br /> <img src='%s' /> -</body></html>""" % (url("other"), url("else"), - url("files/made_with_cherrypy_small.png")) +</body></html>""" % (url('other'), url('else'), + url('files/made_with_cherrypy_small.png')) @cherrypy.expose def default(self, *args, **kwargs): - return "args: %s kwargs: %s" % (args, kwargs) + return 'args: %s kwargs: %s' % (args, kwargs) @cherrypy.expose def other(self, a=2, b='bananas', c=None): cherrypy.response.headers['Content-Type'] = 'text/plain' if c is None: - return "Have %d %s." % (int(a), b) + return 'Have %d %s.' % (int(a), b) else: - return "Have %d %s, %s." % (int(a), b, c) + return 'Have %d %s, %s.' % (int(a), b, c) files = tools.staticdir.handler( - section="/files", - dir=os.path.join(local_dir, "static"), + section='/files', + dir=os.path.join(local_dir, 'static'), # Ignore .php files, etc. match=r'\.(css|gif|html?|ico|jpe?g|js|png|swf|xml)$', ) diff --git a/cherrypy/test/_test_decorators.py b/cherrypy/test/_test_decorators.py index 06fbf0cb..f6b3e1b1 100644 --- a/cherrypy/test/_test_decorators.py +++ b/cherrypy/test/_test_decorators.py @@ -9,23 +9,23 @@ class ExposeExamples(object): @expose def no_call(self): - return "Mr E. R. Bradshaw" + return 'Mr E. R. Bradshaw' @expose() def call_empty(self): - return "Mrs. B.J. Smegma" + return 'Mrs. B.J. Smegma' - @expose("call_alias") + @expose('call_alias') def nesbitt(self): - return "Mr Nesbitt" + return 'Mr Nesbitt' - @expose(["alias1", "alias2"]) + @expose(['alias1', 'alias2']) def andrews(self): - return "Mr Ken Andrews" + return 'Mr Ken Andrews' - @expose(alias="alias3") + @expose(alias='alias3') def watson(self): - return "Mr. and Mrs. Watson" + return 'Mr. and Mrs. Watson' class ToolExamples(object): @@ -37,4 +37,4 @@ class ToolExamples(object): @cherrypy.config(**{'response.stream': True}) @tools.response_headers(headers=[('Content-Type', 'application/data')]) def blah(self): - yield ntob("blah") + yield ntob('blah') diff --git a/cherrypy/test/_test_states_demo.py b/cherrypy/test/_test_states_demo.py index a4b64e71..d50888ef 100644 --- a/cherrypy/test/_test_states_demo.py +++ b/cherrypy/test/_test_states_demo.py @@ -11,11 +11,11 @@ class Root: @cherrypy.expose def index(self): - return "Hello World" + return 'Hello World' @cherrypy.expose def mtimes(self): - return repr(cherrypy.engine.publish("Autoreloader", "mtimes")) + return repr(cherrypy.engine.publish('Autoreloader', 'mtimes')) @cherrypy.expose def pid(self): @@ -36,9 +36,9 @@ class Root: def unsub_sig(): - cherrypy.log("unsubsig: %s" % cherrypy.config.get('unsubsig', False)) + cherrypy.log('unsubsig: %s' % cherrypy.config.get('unsubsig', False)) if cherrypy.config.get('unsubsig', False): - cherrypy.log("Unsubscribing the default cherrypy signal handler") + cherrypy.log('Unsubscribing the default cherrypy signal handler') cherrypy.engine.signal_handler.unsubscribe() try: from signal import signal, SIGTERM @@ -46,9 +46,9 @@ def unsub_sig(): pass else: def old_term_handler(signum=None, frame=None): - cherrypy.log("I am an old SIGTERM handler.") + cherrypy.log('I am an old SIGTERM handler.') sys.exit(0) - cherrypy.log("Subscribing the new one.") + cherrypy.log('Subscribing the new one.') signal(SIGTERM, old_term_handler) cherrypy.engine.subscribe('start', unsub_sig, priority=100) @@ -61,7 +61,7 @@ cherrypy.engine.subscribe('start', starterror, priority=6) def log_test_case_name(): if cherrypy.config.get('test_case_name', False): - cherrypy.log("STARTED FROM: %s" % + cherrypy.log('STARTED FROM: %s' % cherrypy.config.get('test_case_name')) cherrypy.engine.subscribe('start', log_test_case_name, priority=6) diff --git a/cherrypy/test/benchmark.py b/cherrypy/test/benchmark.py index e29fb7a4..03c3c837 100644 --- a/cherrypy/test/benchmark.py +++ b/cherrypy/test/benchmark.py @@ -35,9 +35,9 @@ from cherrypy.lib import httputil curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) -AB_PATH = "" -APACHE_PATH = "apache" -SCRIPT_NAME = "/cpbench/users/rdelon/apps/blog" +AB_PATH = '' +APACHE_PATH = 'apache' +SCRIPT_NAME = '/cpbench/users/rdelon/apps/blog' __all__ = ['ABSession', 'Root', 'print_report', 'run_standard_benchmarks', 'safe_threads', @@ -68,13 +68,13 @@ class Root: @cherrypy.expose def hello(self): - return "Hello, world\r\n" + return 'Hello, world\r\n' @cherrypy.expose def sizer(self, size): resp = size_cache.get(size, None) if resp is None: - size_cache[size] = resp = "X" * int(size) + size_cache[size] = resp = 'X' * int(size) return resp @@ -107,20 +107,20 @@ class NullRequest: """A null HTTP request class, returning 200 and an empty body.""" - def __init__(self, local, remote, scheme="http"): + def __init__(self, local, remote, scheme='http'): pass def close(self): pass def run(self, method, path, query_string, protocol, headers, rfile): - cherrypy.response.status = "200 OK" - cherrypy.response.header_list = [("Content-Type", 'text/html'), - ("Server", "Null CherryPy"), - ("Date", httputil.HTTPDate()), - ("Content-Length", "0"), + cherrypy.response.status = '200 OK' + cherrypy.response.header_list = [('Content-Type', 'text/html'), + ('Server', 'Null CherryPy'), + ('Date', httputil.HTTPDate()), + ('Content-Length', '0'), ] - cherrypy.response.body = [""] + cherrypy.response.body = [''] return cherrypy.response @@ -202,7 +202,7 @@ Finished 1000 requests ntob(r'^Transfer rate:\s*([0-9.]+)')) ] - def __init__(self, path=SCRIPT_NAME + "/hello", requests=1000, + def __init__(self, path=SCRIPT_NAME + '/hello', requests=1000, concurrency=10): self.path = path self.requests = requests @@ -215,13 +215,13 @@ Finished 1000 requests # Don't use "localhost". # Cf # http://mail.python.org/pipermail/python-win32/2008-March/007050.html - return ("-k -n %s -c %s http://127.0.0.1:%s%s" % + return ('-k -n %s -c %s http://127.0.0.1:%s%s' % (self.requests, self.concurrency, port, self.path)) def run(self): # Parse output of ab, setting attributes on self try: - self.output = _cpmodpy.read_process(AB_PATH or "ab", self.args()) + self.output = _cpmodpy.read_process(AB_PATH or 'ab', self.args()) except: print(_cperror.format_exc()) raise @@ -236,12 +236,12 @@ Finished 1000 requests safe_threads = (25, 50, 100, 200, 400) -if sys.platform in ("win32",): +if sys.platform in ('win32',): # For some reason, ab crashes with > 50 threads on my Win2k laptop. safe_threads = (10, 20, 30, 40, 50) -def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads): +def thread_report(path=SCRIPT_NAME + '/hello', concurrency=safe_threads): sess = ABSession(path) attrs, names, patterns = list(zip(*sess.parse_patterns)) avg = dict.fromkeys(attrs, 0.0) @@ -264,7 +264,7 @@ def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads): yield row # Add a row of averages. - yield ["Average"] + [str(avg[attr] / len(concurrency)) for attr in attrs] + yield ['Average'] + [str(avg[attr] / len(concurrency)) for attr in attrs] def size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000), @@ -273,33 +273,33 @@ def size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000), attrs, names, patterns = list(zip(*sess.parse_patterns)) yield ('bytes',) + names for sz in sizes: - sess.path = "%s/sizer?size=%s" % (SCRIPT_NAME, sz) + sess.path = '%s/sizer?size=%s' % (SCRIPT_NAME, sz) sess.run() yield [sz] + [getattr(sess, attr) for attr in attrs] def print_report(rows): for row in rows: - print("") + print('') for i, val in enumerate(row): - sys.stdout.write(str(val).rjust(10) + " | ") - print("") + sys.stdout.write(str(val).rjust(10) + ' | ') + print('') def run_standard_benchmarks(): - print("") - print("Client Thread Report (1000 requests, 14 byte response body, " - "%s server threads):" % cherrypy.server.thread_pool) + print('') + print('Client Thread Report (1000 requests, 14 byte response body, ' + '%s server threads):' % cherrypy.server.thread_pool) print_report(thread_report()) - print("") - print("Client Thread Report (1000 requests, 14 bytes via staticdir, " - "%s server threads):" % cherrypy.server.thread_pool) - print_report(thread_report("%s/static/index.html" % SCRIPT_NAME)) + print('') + print('Client Thread Report (1000 requests, 14 bytes via staticdir, ' + '%s server threads):' % cherrypy.server.thread_pool) + print_report(thread_report('%s/static/index.html' % SCRIPT_NAME)) - print("") - print("Size Report (1000 requests, 50 client threads, " - "%s server threads):" % cherrypy.server.thread_pool) + print('') + print('Size Report (1000 requests, 50 client threads, ' + '%s server threads):' % cherrypy.server.thread_pool) print_report(size_report()) @@ -310,10 +310,10 @@ def startup_modpython(req=None): """ if cherrypy.engine.state == cherrypy._cpengine.STOPPED: if req: - if "nullreq" in req.get_options(): + if 'nullreq' in req.get_options(): cherrypy.engine.request_class = NullRequest cherrypy.engine.response_class = NullResponse - ab_opt = req.get_options().get("ab", "") + ab_opt = req.get_options().get('ab', '') if ab_opt: global AB_PATH AB_PATH = ab_opt @@ -324,27 +324,27 @@ def startup_modpython(req=None): def run_modpython(use_wsgi=False): - print("Starting mod_python...") + print('Starting mod_python...') pyopts = [] # Pass the null and ab=path options through Apache - if "--null" in opts: - pyopts.append(("nullreq", "")) + if '--null' in opts: + pyopts.append(('nullreq', '')) - if "--ab" in opts: - pyopts.append(("ab", opts["--ab"])) + if '--ab' in opts: + pyopts.append(('ab', opts['--ab'])) s = _cpmodpy.ModPythonServer if use_wsgi: - pyopts.append(("wsgi.application", "cherrypy::tree")) + pyopts.append(('wsgi.application', 'cherrypy::tree')) pyopts.append( - ("wsgi.startup", "cherrypy.test.benchmark::startup_modpython")) - handler = "modpython_gateway::handler" + ('wsgi.startup', 'cherrypy.test.benchmark::startup_modpython')) + handler = 'modpython_gateway::handler' s = s(port=54583, opts=pyopts, apache_path=APACHE_PATH, handler=handler) else: pyopts.append( - ("cherrypy.setup", "cherrypy.test.benchmark::startup_modpython")) + ('cherrypy.setup', 'cherrypy.test.benchmark::startup_modpython')) s = s(port=54583, opts=pyopts, apache_path=APACHE_PATH) try: @@ -358,35 +358,35 @@ if __name__ == '__main__': longopts = ['cpmodpy', 'modpython', 'null', 'notests', 'help', 'ab=', 'apache='] try: - switches, args = getopt.getopt(sys.argv[1:], "", longopts) + switches, args = getopt.getopt(sys.argv[1:], '', longopts) opts = dict(switches) except getopt.GetoptError: print(__doc__) sys.exit(2) - if "--help" in opts: + if '--help' in opts: print(__doc__) sys.exit(0) - if "--ab" in opts: + if '--ab' in opts: AB_PATH = opts['--ab'] - if "--notests" in opts: + if '--notests' in opts: # Return without stopping the server, so that the pages # can be tested from a standard web browser. def run(): port = cherrypy.server.socket_port - print("You may now open http://127.0.0.1:%s%s/" % + print('You may now open http://127.0.0.1:%s%s/' % (port, SCRIPT_NAME)) - if "--null" in opts: - print("Using null Request object") + if '--null' in opts: + print('Using null Request object') else: def run(): end = time.time() - start - print("Started in %s seconds" % end) - if "--null" in opts: - print("\nUsing null Request object") + print('Started in %s seconds' % end) + if '--null' in opts: + print('\nUsing null Request object') try: try: run_standard_benchmarks() @@ -396,7 +396,7 @@ if __name__ == '__main__': finally: cherrypy.engine.exit() - print("Starting CherryPy app server...") + print('Starting CherryPy app server...') class NullWriter(object): @@ -408,12 +408,12 @@ if __name__ == '__main__': start = time.time() - if "--cpmodpy" in opts: + if '--cpmodpy' in opts: run_modpython() - elif "--modpython" in opts: + elif '--modpython' in opts: run_modpython(use_wsgi=True) else: - if "--null" in opts: + if '--null' in opts: cherrypy.server.request_class = NullRequest cherrypy.server.response_class = NullResponse diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py index 7a979386..6cb82599 100644 --- a/cherrypy/test/helper.py +++ b/cherrypy/test/helper.py @@ -37,7 +37,7 @@ def get_tst_config(overconf={}): if _testconfig is None: conf = { 'scheme': 'http', - 'protocol': "HTTP/1.1", + 'protocol': 'HTTP/1.1', 'port': 54583, 'host': '127.0.0.1', 'validate': False, @@ -98,9 +98,9 @@ class LocalSupervisor(Supervisor): # place that i've found so far that I KNOW is early enough to set this. cherrypy.config.update({'log.screen': False}) engine = cherrypy.engine - if hasattr(engine, "signal_handler"): + if hasattr(engine, 'signal_handler'): engine.signal_handler.subscribe() - if hasattr(engine, "console_control_handler"): + if hasattr(engine, 'console_control_handler'): engine.console_control_handler.subscribe() #engine.subscribe('log', log_to_stderr) @@ -135,24 +135,24 @@ class NativeServerSupervisor(LocalSupervisor): """Server supervisor for the builtin HTTP server.""" - httpserver_class = "cherrypy._cpnative_server.CPHTTPServer" + httpserver_class = 'cherrypy._cpnative_server.CPHTTPServer' using_apache = False using_wsgi = False def __str__(self): - return "Builtin HTTP Server on %s:%s" % (self.host, self.port) + return 'Builtin HTTP Server on %s:%s' % (self.host, self.port) class LocalWSGISupervisor(LocalSupervisor): """Server supervisor for the builtin WSGI server.""" - httpserver_class = "cherrypy._cpwsgi_server.CPWSGIServer" + httpserver_class = 'cherrypy._cpwsgi_server.CPWSGIServer' using_apache = False using_wsgi = True def __str__(self): - return "Builtin WSGI Server on %s:%s" % (self.host, self.port) + return 'Builtin WSGI Server on %s:%s' % (self.host, self.port) def sync_apps(self): """Hook a new WSGI app into the origin server.""" @@ -168,7 +168,7 @@ class LocalWSGISupervisor(LocalSupervisor): from wsgiref import validate except ImportError: warnings.warn( - "Error importing wsgiref. The validator will not run.") + 'Error importing wsgiref. The validator will not run.') else: # wraps the app in the validator app = validate.validator(app) @@ -213,8 +213,8 @@ def get_wsgi_u_supervisor(**options): class CPWebCase(webtest.WebCase): - script_name = "" - scheme = "http" + script_name = '' + scheme = 'http' available_servers = {'wsgi': LocalWSGISupervisor, 'wsgi_u': get_wsgi_u_supervisor, @@ -225,19 +225,19 @@ class CPWebCase(webtest.WebCase): 'modfcgid': get_modfcgid_supervisor, 'modfastcgi': get_modfastcgi_supervisor, } - default_server = "wsgi" + default_server = 'wsgi' @classmethod def _setup_server(cls, supervisor, conf): v = sys.version.split()[0] - log.info("Python version used to run this test script: %s" % v) - log.info("CherryPy version: %s" % cherrypy.__version__) - if supervisor.scheme == "https": - ssl = " (ssl)" + log.info('Python version used to run this test script: %s' % v) + log.info('CherryPy version: %s' % cherrypy.__version__) + if supervisor.scheme == 'https': + ssl = ' (ssl)' else: - ssl = "" - log.info("HTTP server version: %s%s" % (supervisor.protocol, ssl)) - log.info("PID: %s" % os.getpid()) + ssl = '' + log.info('HTTP server version: %s%s' % (supervisor.protocol, ssl)) + log.info('PID: %s' % os.getpid()) cherrypy.server.using_apache = supervisor.using_apache cherrypy.server.using_wsgi = supervisor.using_wsgi @@ -254,9 +254,9 @@ class CPWebCase(webtest.WebCase): baseconf.update({'server.socket_host': supervisor.host, 'server.socket_port': supervisor.port, 'server.protocol_version': supervisor.protocol, - 'environment': "test_suite", + 'environment': 'test_suite', }) - if supervisor.scheme == "https": + if supervisor.scheme == 'https': #baseconf['server.ssl_module'] = 'builtin' baseconf['server.ssl_certificate'] = serverpem baseconf['server.ssl_private_key'] = serverpem @@ -267,7 +267,7 @@ class CPWebCase(webtest.WebCase): # exactly like each test module does, because a relative import # would stick a second instance of webtest in sys.modules, # and we wouldn't be able to globally override the port anymore. - if supervisor.scheme == "https": + if supervisor.scheme == 'https': webtest.WebCase.HTTP_CONN = HTTPSConnection return baseconf @@ -314,29 +314,29 @@ class CPWebCase(webtest.WebCase): if not self.do_gc_test: return - self.getPage("/gc/stats") + self.getPage('/gc/stats') try: - self.assertBody("Statistics:") + self.assertBody('Statistics:') except Exception: - "Failures occur intermittently. See #1420" + 'Failures occur intermittently. See #1420' def prefix(self): - return self.script_name.rstrip("/") + return self.script_name.rstrip('/') def base(self): - if ((self.scheme == "http" and self.PORT == 80) or - (self.scheme == "https" and self.PORT == 443)): - port = "" + if ((self.scheme == 'http' and self.PORT == 80) or + (self.scheme == 'https' and self.PORT == 443)): + port = '' else: - port = ":%s" % self.PORT + port = ':%s' % self.PORT - return "%s://%s%s%s" % (self.scheme, self.HOST, port, - self.script_name.rstrip("/")) + return '%s://%s%s%s' % (self.scheme, self.HOST, port, + self.script_name.rstrip('/')) def exit(self): sys.exit() - def getPage(self, url, headers=None, method="GET", body=None, + def getPage(self, url, headers=None, method='GET', body=None, protocol=None, raise_subcls=None): """Open the url. Return status, headers, body. @@ -453,7 +453,7 @@ log.access_file: r'%(access_log)s' self.host = socket_host or cherrypy.server.socket_host self.port = socket_port or cherrypy.server.socket_port - def write_conf(self, extra=""): + def write_conf(self, extra=''): if self.ssl: serverpem = os.path.join(thisdir, 'test.pem') ssl = """ @@ -461,7 +461,7 @@ server.ssl_certificate: r'%s' server.ssl_private_key: r'%s' """ % (serverpem, serverpem) else: - ssl = "" + ssl = '' conf = self.config_template % { 'host': self.host, diff --git a/cherrypy/test/logtest.py b/cherrypy/test/logtest.py index 27feac86..b6201f2a 100644 --- a/cherrypy/test/logtest.py +++ b/cherrypy/test/logtest.py @@ -46,47 +46,47 @@ class LogCase(object): logfile = None lastmarker = None - markerPrefix = ntob("test suite marker: ") + markerPrefix = ntob('test suite marker: ') def _handleLogError(self, msg, data, marker, pattern): - print("") - print(" ERROR: %s" % msg) + print('') + print(' ERROR: %s' % msg) if not self.interactive: raise self.failureException(msg) - p = (" Show: " - "[L]og [M]arker [P]attern; " - "[I]gnore, [R]aise, or sys.e[X]it >> ") + p = (' Show: ' + '[L]og [M]arker [P]attern; ' + '[I]gnore, [R]aise, or sys.e[X]it >> ') sys.stdout.write(p + ' ') # ARGH sys.stdout.flush() while True: i = getchar().upper() - if i not in "MPLIRX": + if i not in 'MPLIRX': continue print(i.upper()) # Also prints new line - if i == "L": + if i == 'L': for x, line in enumerate(data): if (x + 1) % self.console_height == 0: # The \r and comma should make the next line overwrite - sys.stdout.write("<-- More -->\r ") + sys.stdout.write('<-- More -->\r ') m = getchar().lower() # Erase our "More" prompt - sys.stdout.write(" \r ") - if m == "q": + sys.stdout.write(' \r ') + if m == 'q': break print(line.rstrip()) - elif i == "M": + elif i == 'M': print(repr(marker or self.lastmarker)) - elif i == "P": + elif i == 'P': print(repr(pattern)) - elif i == "I": + elif i == 'I': # return without raising the normal exception return - elif i == "R": + elif i == 'R': raise self.failureException(msg) - elif i == "X": + elif i == 'X': self.exit() sys.stdout.write(p + ' ') @@ -95,7 +95,7 @@ class LogCase(object): def emptyLog(self): """Overwrite self.logfile with 0 bytes.""" - open(self.logfile, 'wb').write("") + open(self.logfile, 'wb').write('') def markLog(self, key=None): """Insert a marker line into the log and set self.lastmarker.""" @@ -104,7 +104,7 @@ class LogCase(object): self.lastmarker = key open(self.logfile, 'ab+').write( - ntob("%s%s\n" % (self.markerPrefix, key), "utf-8")) + ntob('%s%s\n' % (self.markerPrefix, key), 'utf-8')) def _read_marked_region(self, marker=None): """Return lines from self.logfile in the marked region. @@ -145,7 +145,7 @@ class LogCase(object): for logline in data: if line in logline: return - msg = "%r not found in log" % line + msg = '%r not found in log' % line self._handleLogError(msg, data, marker, line) def assertNotInLog(self, line, marker=None): @@ -158,7 +158,7 @@ class LogCase(object): data = self._read_marked_region(marker) for logline in data: if line in logline: - msg = "%r found in log" % line + msg = '%r found in log' % line self._handleLogError(msg, data, marker, line) def assertLog(self, sliceargs, lines, marker=None): @@ -176,10 +176,10 @@ class LogCase(object): if isinstance(lines, six.text_type): lines = lines.encode('utf-8') if lines not in data[sliceargs]: - msg = "%r not found on log line %r" % (lines, sliceargs) + msg = '%r not found on log line %r' % (lines, sliceargs) self._handleLogError( msg, - [data[sliceargs], "--EXTRA CONTEXT--"] + data[ + [data[sliceargs], '--EXTRA CONTEXT--'] + data[ sliceargs + 1:sliceargs + 6], marker, lines) @@ -196,5 +196,5 @@ class LogCase(object): if isinstance(line, six.text_type): line = line.encode('utf-8') if line not in logline: - msg = "%r not found in log" % line + msg = '%r not found in log' % line self._handleLogError(msg, data[start:stop], marker, line) diff --git a/cherrypy/test/modfastcgi.py b/cherrypy/test/modfastcgi.py index 83e7add1..79ec3d18 100644 --- a/cherrypy/test/modfastcgi.py +++ b/cherrypy/test/modfastcgi.py @@ -43,11 +43,11 @@ from cherrypy.test import helper curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) -def read_process(cmd, args=""): - pipein, pipeout = os.popen4("%s %s" % (cmd, args)) +def read_process(cmd, args=''): + pipein, pipeout = os.popen4('%s %s' % (cmd, args)) try: firstline = pipeout.readline() - if (re.search(r"(not recognized|No such file|not found)", firstline, + if (re.search(r'(not recognized|No such file|not found)', firstline, re.IGNORECASE)): raise IOError('%s must be on your system path.' % cmd) output = firstline + pipeout.read() @@ -56,8 +56,8 @@ def read_process(cmd, args=""): return output -APACHE_PATH = "apache2ctl" -CONF_PATH = "fastcgi.conf" +APACHE_PATH = 'apache2ctl' +CONF_PATH = 'fastcgi.conf' conf_fastcgi = """ # Apache2 server conf file for testing CherryPy with mod_fastcgi. @@ -87,13 +87,13 @@ def erase_script_name(environ, start_response): class ModFCGISupervisor(helper.LocalWSGISupervisor): - httpserver_class = "cherrypy.process.servers.FlupFCGIServer" + httpserver_class = 'cherrypy.process.servers.FlupFCGIServer' using_apache = True using_wsgi = True template = conf_fastcgi def __str__(self): - return "FCGI Server on %s:%s" % (self.host, self.port) + return 'FCGI Server on %s:%s' % (self.host, self.port) def start(self, modulename): cherrypy.server.httpserver = servers.FlupFCGIServer( @@ -122,13 +122,13 @@ class ModFCGISupervisor(helper.LocalWSGISupervisor): finally: f.close() - result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf) + result = read_process(APACHE_PATH, '-k start -f %s' % fcgiconf) if result: print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" - read_process(APACHE_PATH, "-k stop") + read_process(APACHE_PATH, '-k stop') helper.LocalWSGISupervisor.stop(self) def sync_apps(self): diff --git a/cherrypy/test/modfcgid.py b/cherrypy/test/modfcgid.py index 17188e51..d101bd67 100644 --- a/cherrypy/test/modfcgid.py +++ b/cherrypy/test/modfcgid.py @@ -44,11 +44,11 @@ from cherrypy.test import helper curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) -def read_process(cmd, args=""): - pipein, pipeout = os.popen4("%s %s" % (cmd, args)) +def read_process(cmd, args=''): + pipein, pipeout = os.popen4('%s %s' % (cmd, args)) try: firstline = pipeout.readline() - if (re.search(r"(not recognized|No such file|not found)", firstline, + if (re.search(r'(not recognized|No such file|not found)', firstline, re.IGNORECASE)): raise IOError('%s must be on your system path.' % cmd) output = firstline + pipeout.read() @@ -57,8 +57,8 @@ def read_process(cmd, args=""): return output -APACHE_PATH = "httpd" -CONF_PATH = "fcgi.conf" +APACHE_PATH = 'httpd' +CONF_PATH = 'fcgi.conf' conf_fcgid = """ # Apache2 server conf file for testing CherryPy with mod_fcgid. @@ -84,7 +84,7 @@ class ModFCGISupervisor(helper.LocalSupervisor): template = conf_fcgid def __str__(self): - return "FCGI Server on %s:%s" % (self.host, self.port) + return 'FCGI Server on %s:%s' % (self.host, self.port) def start(self, modulename): cherrypy.server.httpserver = servers.FlupFCGIServer( @@ -111,13 +111,13 @@ class ModFCGISupervisor(helper.LocalSupervisor): finally: f.close() - result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf) + result = read_process(APACHE_PATH, '-k start -f %s' % fcgiconf) if result: print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" - read_process(APACHE_PATH, "-k stop") + read_process(APACHE_PATH, '-k stop') helper.LocalServer.stop(self) def sync_apps(self): diff --git a/cherrypy/test/modpy.py b/cherrypy/test/modpy.py index c4772683..6da9c536 100644 --- a/cherrypy/test/modpy.py +++ b/cherrypy/test/modpy.py @@ -42,11 +42,11 @@ from cherrypy.test import helper curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) -def read_process(cmd, args=""): - pipein, pipeout = os.popen4("%s %s" % (cmd, args)) +def read_process(cmd, args=''): + pipein, pipeout = os.popen4('%s %s' % (cmd, args)) try: firstline = pipeout.readline() - if (re.search(r"(not recognized|No such file|not found)", firstline, + if (re.search(r'(not recognized|No such file|not found)', firstline, re.IGNORECASE)): raise IOError('%s must be on your system path.' % cmd) output = firstline + pipeout.read() @@ -55,8 +55,8 @@ def read_process(cmd, args=""): return output -APACHE_PATH = "httpd" -CONF_PATH = "test_mp.conf" +APACHE_PATH = 'httpd' +CONF_PATH = 'test_mp.conf' conf_modpython_gateway = """ # Apache2 server conf file for testing CherryPy with modpython_gateway. @@ -99,7 +99,7 @@ class ModPythonSupervisor(helper.Supervisor): template = None def __str__(self): - return "ModPython Server on %s:%s" % (self.host, self.port) + return 'ModPython Server on %s:%s' % (self.host, self.port) def start(self, modulename): mpconf = CONF_PATH @@ -114,13 +114,13 @@ class ModPythonSupervisor(helper.Supervisor): finally: f.close() - result = read_process(APACHE_PATH, "-k start -f %s" % mpconf) + result = read_process(APACHE_PATH, '-k start -f %s' % mpconf) if result: print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" - read_process(APACHE_PATH, "-k stop") + read_process(APACHE_PATH, '-k stop') loaded = False @@ -134,9 +134,9 @@ def wsgisetup(req): import cherrypy cherrypy.config.update({ - "log.error_file": os.path.join(curdir, "test.log"), - "environment": "test_suite", - "server.socket_host": options['socket_host'], + 'log.error_file': os.path.join(curdir, 'test.log'), + 'environment': 'test_suite', + 'server.socket_host': options['socket_host'], }) modname = options['testmod'] @@ -157,9 +157,9 @@ def cpmodpysetup(req): import cherrypy cherrypy.config.update({ - "log.error_file": os.path.join(curdir, "test.log"), - "environment": "test_suite", - "server.socket_host": options['socket_host'], + 'log.error_file': os.path.join(curdir, 'test.log'), + 'environment': 'test_suite', + 'server.socket_host': options['socket_host'], }) from mod_python import apache return apache.OK diff --git a/cherrypy/test/modwsgi.py b/cherrypy/test/modwsgi.py index 29816c60..0177c1c0 100644 --- a/cherrypy/test/modwsgi.py +++ b/cherrypy/test/modwsgi.py @@ -43,11 +43,11 @@ from cherrypy.test import helper, webtest curdir = os.path.abspath(os.path.dirname(__file__)) -def read_process(cmd, args=""): - pipein, pipeout = os.popen4("%s %s" % (cmd, args)) +def read_process(cmd, args=''): + pipein, pipeout = os.popen4('%s %s' % (cmd, args)) try: firstline = pipeout.readline() - if (re.search(r"(not recognized|No such file|not found)", firstline, + if (re.search(r'(not recognized|No such file|not found)', firstline, re.IGNORECASE)): raise IOError('%s must be on your system path.' % cmd) output = firstline + pipeout.read() @@ -57,11 +57,11 @@ def read_process(cmd, args=""): if sys.platform == 'win32': - APACHE_PATH = "httpd" + APACHE_PATH = 'httpd' else: - APACHE_PATH = "apache" + APACHE_PATH = 'apache' -CONF_PATH = "test_mw.conf" +CONF_PATH = 'test_mw.conf' conf_modwsgi = r""" # Apache2 server conf file for testing CherryPy with modpython_gateway. @@ -98,7 +98,7 @@ class ModWSGISupervisor(helper.Supervisor): template = conf_modwsgi def __str__(self): - return "ModWSGI Server on %s:%s" % (self.host, self.port) + return 'ModWSGI Server on %s:%s' % (self.host, self.port) def start(self, modulename): mpconf = CONF_PATH @@ -114,19 +114,19 @@ class ModWSGISupervisor(helper.Supervisor): finally: f.close() - result = read_process(APACHE_PATH, "-k start -f %s" % mpconf) + result = read_process(APACHE_PATH, '-k start -f %s' % mpconf) if result: print(result) # Make a request so mod_wsgi starts up our app. # If we don't, concurrent initial requests will 404. - cherrypy._cpserver.wait_for_occupied_port("127.0.0.1", self.port) + cherrypy._cpserver.wait_for_occupied_port('127.0.0.1', self.port) webtest.openURL('/ihopetheresnodefault', port=self.port) time.sleep(1) def stop(self): """Gracefully shutdown a server that is serving forever.""" - read_process(APACHE_PATH, "-k stop") + read_process(APACHE_PATH, '-k stop') loaded = False @@ -137,15 +137,15 @@ def application(environ, start_response): global loaded if not loaded: loaded = True - modname = "cherrypy.test." + environ['testmod'] + modname = 'cherrypy.test.' + environ['testmod'] mod = __import__(modname, globals(), locals(), ['']) mod.setup_server() cherrypy.config.update({ - "log.error_file": os.path.join(curdir, "test.error.log"), - "log.access_file": os.path.join(curdir, "test.access.log"), - "environment": "test_suite", - "engine.SIGHUP": None, - "engine.SIGTERM": None, + 'log.error_file': os.path.join(curdir, 'test.error.log'), + 'log.access_file': os.path.join(curdir, 'test.access.log'), + 'environment': 'test_suite', + 'engine.SIGHUP': None, + 'engine.SIGTERM': None, }) return cherrypy.tree(environ, start_response) diff --git a/cherrypy/test/sessiondemo.py b/cherrypy/test/sessiondemo.py index 4b3d1222..a8585583 100755 --- a/cherrypy/test/sessiondemo.py +++ b/cherrypy/test/sessiondemo.py @@ -123,7 +123,7 @@ class Root(object): 'reqcookie': cherrypy.request.cookie.output(), 'sessiondata': copyitems(cherrypy.session), 'servertime': ( - datetime.utcnow().strftime("%Y/%m/%d %H:%M") + " UTC" + datetime.utcnow().strftime('%Y/%m/%d %H:%M') + ' UTC' ), 'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()), 'cpversion': cherrypy.__version__, diff --git a/cherrypy/test/test_auth_basic.py b/cherrypy/test/test_auth_basic.py index b70f2902..48582ec2 100644 --- a/cherrypy/test/test_auth_basic.py +++ b/cherrypy/test/test_auth_basic.py @@ -18,7 +18,7 @@ class BasicAuthTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "This is public." + return 'This is public.' class BasicProtected: @@ -61,13 +61,13 @@ class BasicAuthTest(helper.CPWebCase): cherrypy.tree.mount(root, config=conf) def testPublic(self): - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html;charset=utf-8') self.assertBody('This is public.') def testBasic(self): - self.getPage("/basic/") + self.getPage('/basic/') self.assertStatus(401) self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"') @@ -81,7 +81,7 @@ class BasicAuthTest(helper.CPWebCase): self.assertBody("Hello xuser, you've been authorized.") def testBasic2(self): - self.getPage("/basic2/") + self.getPage('/basic2/') self.assertStatus(401) self.assertHeader('WWW-Authenticate', 'Basic realm="wonderland"') diff --git a/cherrypy/test/test_auth_digest.py b/cherrypy/test/test_auth_digest.py index bcb9431f..8f71a8dc 100644 --- a/cherrypy/test/test_auth_digest.py +++ b/cherrypy/test/test_auth_digest.py @@ -17,7 +17,7 @@ class DigestAuthTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "This is public." + return 'This is public.' class DigestProtected: @@ -41,25 +41,25 @@ class DigestAuthTest(helper.CPWebCase): cherrypy.tree.mount(root, config=conf) def testPublic(self): - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html;charset=utf-8') self.assertBody('This is public.') def testDigest(self): - self.getPage("/digest/") + self.getPage('/digest/') self.assertStatus(401) value = None for k, v in self.headers: - if k.lower() == "www-authenticate": - if v.startswith("Digest"): + if k.lower() == 'www-authenticate': + if v.startswith('Digest'): value = v break if value is None: self._handlewebError( - "Digest authentification scheme was not found") + 'Digest authentification scheme was not found') value = value[7:] items = value.split(', ') @@ -68,7 +68,7 @@ class DigestAuthTest(helper.CPWebCase): key, value = item.split('=') tokens[key.lower()] = value - missing_msg = "%s is missing" + missing_msg = '%s is missing' bad_value_msg = "'%s' was expecting '%s' but found '%s'" nonce = None if 'realm' not in tokens: diff --git a/cherrypy/test/test_bus.py b/cherrypy/test/test_bus.py index bd102b02..6026b47e 100644 --- a/cherrypy/test/test_bus.py +++ b/cherrypy/test/test_bus.py @@ -5,7 +5,7 @@ import unittest from cherrypy.process import wspbus -msg = "Listener %d on channel %s: %s." +msg = 'Listener %d on channel %s: %s.' class PublishSubscribeTests(unittest.TestCase): @@ -190,7 +190,7 @@ class BusMethodTests(unittest.TestCase): # The wait method MUST wait for the given state(s). if b.state not in states: - self.fail("State %r not in %r" % (b.state, states)) + self.fail('State %r not in %r' % (b.state, states)) def test_block(self): b = wspbus.Bus() @@ -229,19 +229,19 @@ class BusMethodTests(unittest.TestCase): events = [] def f(*args, **kwargs): - events.append(("f", args, kwargs)) + events.append(('f', args, kwargs)) def g(): - events.append("g") - b.subscribe("start", g) - b.start_with_callback(f, (1, 3, 5), {"foo": "bar"}) + events.append('g') + b.subscribe('start', g) + b.start_with_callback(f, (1, 3, 5), {'foo': 'bar'}) # Give wait() time to run f() time.sleep(0.2) # The callback method MUST wait for the STARTED state. self.assertEqual(b.state, b.states.STARTED) # The callback method MUST run after all start methods. - self.assertEqual(events, ["g", ("f", (1, 3, 5), {"foo": "bar"})]) + self.assertEqual(events, ['g', ('f', (1, 3, 5), {'foo': 'bar'})]) finally: b.exit() @@ -252,7 +252,7 @@ class BusMethodTests(unittest.TestCase): # Try a normal message. expected = [] - for msg in ["O mah darlin'"] * 3 + ["Clementiiiiiiiine"]: + for msg in ["O mah darlin'"] * 3 + ['Clementiiiiiiiine']: b.log(msg) expected.append(msg) self.assertLog(expected) @@ -261,14 +261,14 @@ class BusMethodTests(unittest.TestCase): try: foo except NameError: - b.log("You are lost and gone forever", traceback=True) + b.log('You are lost and gone forever', traceback=True) lastmsg = self._log_entries[-1] - if "Traceback" not in lastmsg or "NameError" not in lastmsg: - self.fail("Last log message %r did not contain " - "the expected traceback." % lastmsg) + if 'Traceback' not in lastmsg or 'NameError' not in lastmsg: + self.fail('Last log message %r did not contain ' + 'the expected traceback.' % lastmsg) else: - self.fail("NameError was not raised as expected.") + self.fail('NameError was not raised as expected.') -if __name__ == "__main__": +if __name__ == '__main__': unittest.main() diff --git a/cherrypy/test/test_caching.py b/cherrypy/test/test_caching.py index ac559793..caec042f 100644 --- a/cherrypy/test/test_caching.py +++ b/cherrypy/test/test_caching.py @@ -36,13 +36,13 @@ class CacheTest(helper.CPWebCase): @cherrypy.expose def index(self): self.counter += 1 - msg = "visit #%s" % self.counter + msg = 'visit #%s' % self.counter return msg @cherrypy.expose def control(self): self.control_counter += 1 - return "visit #%s" % self.control_counter + return 'visit #%s' % self.control_counter @cherrypy.expose def a_gif(self): @@ -77,7 +77,7 @@ class CacheTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "visit #%s" % next(self.counter) + return 'visit #%s' % next(self.counter) @cherrypy.config(**{ 'tools.expires.on': True, @@ -94,13 +94,13 @@ class CacheTest(helper.CPWebCase): cherrypy.response.headers['Etag'] = 'bibbitybobbityboo' self._cp_config['tools.expires.force'] = True self._cp_config['tools.expires.secs'] = 0 - return "being forceful" + return 'being forceful' @cherrypy.expose def dynamic(self): cherrypy.response.headers['Etag'] = 'bibbitybobbityboo' cherrypy.response.headers['Cache-Control'] = 'private' - return "D-d-d-dynamic!" + return 'D-d-d-dynamic!' @cherrypy.expose def cacheable(self): @@ -112,7 +112,7 @@ class CacheTest(helper.CPWebCase): def specific(self): cherrypy.response.headers[ 'Etag'] = 'need_this_to_make_me_cacheable' - return "I am being specific" + return 'I am being specific' class Foo(object): pass @@ -122,182 +122,182 @@ class CacheTest(helper.CPWebCase): def wrongtype(self): cherrypy.response.headers[ 'Etag'] = 'need_this_to_make_me_cacheable' - return "Woops" + return 'Woops' cherrypy.tree.mount(Root()) - cherrypy.tree.mount(UnCached(), "/expires") - cherrypy.tree.mount(VaryHeaderCachingServer(), "/varying_headers") + cherrypy.tree.mount(UnCached(), '/expires') + cherrypy.tree.mount(VaryHeaderCachingServer(), '/varying_headers') cherrypy.config.update({'tools.gzip.on': True}) def testCaching(self): elapsed = 0.0 for trial in range(10): - self.getPage("/") + self.getPage('/') # The response should be the same every time, # except for the Age response header. self.assertBody('visit #1') if trial != 0: - age = int(self.assertHeader("Age")) + age = int(self.assertHeader('Age')) self.assert_(age >= elapsed) elapsed = age # POST, PUT, DELETE should not be cached. - self.getPage("/", method="POST") + self.getPage('/', method='POST') self.assertBody('visit #2') # Because gzip is turned on, the Vary header should always Vary for # content-encoding self.assertHeader('Vary', 'Accept-Encoding') # The previous request should have invalidated the cache, # so this request will recalc the response. - self.getPage("/", method="GET") + self.getPage('/', method='GET') self.assertBody('visit #3') # ...but this request should get the cached copy. - self.getPage("/", method="GET") + self.getPage('/', method='GET') self.assertBody('visit #3') - self.getPage("/", method="DELETE") + self.getPage('/', method='DELETE') self.assertBody('visit #4') # The previous request should have invalidated the cache, # so this request will recalc the response. - self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')]) + self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')]) self.assertHeader('Content-Encoding', 'gzip') self.assertHeader('Vary') self.assertEqual( - cherrypy.lib.encoding.decompress(self.body), ntob("visit #5")) + cherrypy.lib.encoding.decompress(self.body), ntob('visit #5')) # Now check that a second request gets the gzip header and gzipped body # This also tests a bug in 3.0 to 3.0.2 whereby the cached, gzipped # response body was being gzipped a second time. - self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')]) + self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')]) self.assertHeader('Content-Encoding', 'gzip') self.assertEqual( - cherrypy.lib.encoding.decompress(self.body), ntob("visit #5")) + cherrypy.lib.encoding.decompress(self.body), ntob('visit #5')) # Now check that a third request that doesn't accept gzip # skips the cache (because the 'Vary' header denies it). - self.getPage("/", method="GET") + self.getPage('/', method='GET') self.assertNoHeader('Content-Encoding') self.assertBody('visit #6') def testVaryHeader(self): - self.getPage("/varying_headers/") - self.assertStatus("200 OK") + self.getPage('/varying_headers/') + self.assertStatus('200 OK') self.assertHeaderItemValue('Vary', 'Our-Varying-Header') self.assertBody('visit #1') # Now check that different 'Vary'-fields don't evict each other. # This test creates 2 requests with different 'Our-Varying-Header' # and then tests if the first one still exists. - self.getPage("/varying_headers/", + self.getPage('/varying_headers/', headers=[('Our-Varying-Header', 'request 2')]) - self.assertStatus("200 OK") + self.assertStatus('200 OK') self.assertBody('visit #2') - self.getPage("/varying_headers/", + self.getPage('/varying_headers/', headers=[('Our-Varying-Header', 'request 2')]) - self.assertStatus("200 OK") + self.assertStatus('200 OK') self.assertBody('visit #2') - self.getPage("/varying_headers/") - self.assertStatus("200 OK") + self.getPage('/varying_headers/') + self.assertStatus('200 OK') self.assertBody('visit #1') def testExpiresTool(self): # test setting an expires header - self.getPage("/expires/specific") - self.assertStatus("200 OK") - self.assertHeader("Expires") + self.getPage('/expires/specific') + self.assertStatus('200 OK') + self.assertHeader('Expires') # test exceptions for bad time values - self.getPage("/expires/wrongtype") + self.getPage('/expires/wrongtype') self.assertStatus(500) - self.assertInBody("TypeError") + self.assertInBody('TypeError') # static content should not have "cache prevention" headers - self.getPage("/expires/index.html") - self.assertStatus("200 OK") - self.assertNoHeader("Pragma") - self.assertNoHeader("Cache-Control") - self.assertHeader("Expires") + self.getPage('/expires/index.html') + self.assertStatus('200 OK') + self.assertNoHeader('Pragma') + self.assertNoHeader('Cache-Control') + self.assertHeader('Expires') # dynamic content that sets indicators should not have # "cache prevention" headers - self.getPage("/expires/cacheable") - self.assertStatus("200 OK") - self.assertNoHeader("Pragma") - self.assertNoHeader("Cache-Control") - self.assertHeader("Expires") + self.getPage('/expires/cacheable') + self.assertStatus('200 OK') + self.assertNoHeader('Pragma') + self.assertNoHeader('Cache-Control') + self.assertHeader('Expires') self.getPage('/expires/dynamic') - self.assertBody("D-d-d-dynamic!") + self.assertBody('D-d-d-dynamic!') # the Cache-Control header should be untouched - self.assertHeader("Cache-Control", "private") - self.assertHeader("Expires") + self.assertHeader('Cache-Control', 'private') + self.assertHeader('Expires') # configure the tool to ignore indicators and replace existing headers - self.getPage("/expires/force") - self.assertStatus("200 OK") + self.getPage('/expires/force') + self.assertStatus('200 OK') # This also gives us a chance to test 0 expiry with no other headers - self.assertHeader("Pragma", "no-cache") - if cherrypy.server.protocol_version == "HTTP/1.1": - self.assertHeader("Cache-Control", "no-cache, must-revalidate") - self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT") + self.assertHeader('Pragma', 'no-cache') + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.assertHeader('Cache-Control', 'no-cache, must-revalidate') + self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') # static content should now have "cache prevention" headers - self.getPage("/expires/index.html") - self.assertStatus("200 OK") - self.assertHeader("Pragma", "no-cache") - if cherrypy.server.protocol_version == "HTTP/1.1": - self.assertHeader("Cache-Control", "no-cache, must-revalidate") - self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT") + self.getPage('/expires/index.html') + self.assertStatus('200 OK') + self.assertHeader('Pragma', 'no-cache') + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.assertHeader('Cache-Control', 'no-cache, must-revalidate') + self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') # the cacheable handler should now have "cache prevention" headers - self.getPage("/expires/cacheable") - self.assertStatus("200 OK") - self.assertHeader("Pragma", "no-cache") - if cherrypy.server.protocol_version == "HTTP/1.1": - self.assertHeader("Cache-Control", "no-cache, must-revalidate") - self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT") + self.getPage('/expires/cacheable') + self.assertStatus('200 OK') + self.assertHeader('Pragma', 'no-cache') + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.assertHeader('Cache-Control', 'no-cache, must-revalidate') + self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') self.getPage('/expires/dynamic') - self.assertBody("D-d-d-dynamic!") + self.assertBody('D-d-d-dynamic!') # dynamic sets Cache-Control to private but it should be # overwritten here ... - self.assertHeader("Pragma", "no-cache") - if cherrypy.server.protocol_version == "HTTP/1.1": - self.assertHeader("Cache-Control", "no-cache, must-revalidate") - self.assertHeader("Expires", "Sun, 28 Jan 2007 00:00:00 GMT") + self.assertHeader('Pragma', 'no-cache') + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.assertHeader('Cache-Control', 'no-cache, must-revalidate') + self.assertHeader('Expires', 'Sun, 28 Jan 2007 00:00:00 GMT') def testLastModified(self): - self.getPage("/a.gif") + self.getPage('/a.gif') self.assertStatus(200) self.assertBody(gif_bytes) - lm1 = self.assertHeader("Last-Modified") + lm1 = self.assertHeader('Last-Modified') # this request should get the cached copy. - self.getPage("/a.gif") + self.getPage('/a.gif') self.assertStatus(200) self.assertBody(gif_bytes) - self.assertHeader("Age") - lm2 = self.assertHeader("Last-Modified") + self.assertHeader('Age') + lm2 = self.assertHeader('Last-Modified') self.assertEqual(lm1, lm2) # this request should match the cached copy, but raise 304. - self.getPage("/a.gif", [('If-Modified-Since', lm1)]) + self.getPage('/a.gif', [('If-Modified-Since', lm1)]) self.assertStatus(304) - self.assertNoHeader("Last-Modified") - if not getattr(cherrypy.server, "using_apache", False): - self.assertHeader("Age") + self.assertNoHeader('Last-Modified') + if not getattr(cherrypy.server, 'using_apache', False): + self.assertHeader('Age') def test_antistampede(self): SECONDS = 4 - slow_url = "/long_process?seconds={SECONDS}".format(**locals()) + slow_url = '/long_process?seconds={SECONDS}'.format(**locals()) # We MUST make an initial synchronous request in order to create the # AntiStampedeCache object, and populate its selecting_headers, # before the actual stampede. self.getPage(slow_url) self.assertBody('success!') - self.getPage("/clear_cache?path=" + quote(slow_url, safe='')) + self.getPage('/clear_cache?path=' + quote(slow_url, safe='')) self.assertStatus(200) start = datetime.datetime.now() @@ -317,23 +317,23 @@ class CacheTest(helper.CPWebCase): self.assertEqualDates(start, finish, seconds=allowance) def test_cache_control(self): - self.getPage("/control") + self.getPage('/control') self.assertBody('visit #1') - self.getPage("/control") + self.getPage('/control') self.assertBody('visit #1') - self.getPage("/control", headers=[('Cache-Control', 'no-cache')]) + self.getPage('/control', headers=[('Cache-Control', 'no-cache')]) self.assertBody('visit #2') - self.getPage("/control") + self.getPage('/control') self.assertBody('visit #2') - self.getPage("/control", headers=[('Pragma', 'no-cache')]) + self.getPage('/control', headers=[('Pragma', 'no-cache')]) self.assertBody('visit #3') - self.getPage("/control") + self.getPage('/control') self.assertBody('visit #3') time.sleep(1) - self.getPage("/control", headers=[('Cache-Control', 'max-age=0')]) + self.getPage('/control', headers=[('Cache-Control', 'max-age=0')]) self.assertBody('visit #4') - self.getPage("/control") + self.getPage('/control') self.assertBody('visit #4') diff --git a/cherrypy/test/test_compat.py b/cherrypy/test/test_compat.py index c31316b1..bfb86e13 100644 --- a/cherrypy/test/test_compat.py +++ b/cherrypy/test/test_compat.py @@ -19,5 +19,5 @@ class StringTester(unittest.TestCase): See #1132 for discussion. """ if six.PY3: - raise nose.SkipTest("Only useful on Python 2") + raise nose.SkipTest('Only useful on Python 2') self.assertRaises(Exception, compat.ntob, 'fight') diff --git a/cherrypy/test/test_config.py b/cherrypy/test/test_config.py index 195872f0..6c9a957a 100644 --- a/cherrypy/test/test_config.py +++ b/cherrypy/test/test_config.py @@ -28,12 +28,12 @@ def setup_server(): cherrypy.config.namespaces['db'] = self.db_namespace def db_namespace(self, k, v): - if k == "scheme": + if k == 'scheme': self.db = v @cherrypy.expose(alias=('global_', 'xyz')) def index(self, key): - return cherrypy.request.config.get(key, "None") + return cherrypy.request.config.get(key, 'None') @cherrypy.expose def repr(self, key): @@ -56,7 +56,7 @@ def setup_server(): @cherrypy.expose def index(self, key): - return cherrypy.request.config.get(key, "None") + return cherrypy.request.config.get(key, 'None') nex = index @cherrypy.expose @@ -74,7 +74,7 @@ def setup_server(): @cherrypy.expose def index(self, key): - return str(cherrypy.request.config.get(key, "None")) + return str(cherrypy.request.config.get(key, 'None')) def raw_namespace(key, value): if key == 'input.map': @@ -133,9 +133,9 @@ tools.staticfile.filename = %r app = cherrypy.tree.mount(root, config=ioconf) app.request_class.namespaces['raw'] = raw_namespace - cherrypy.tree.mount(Another(), "/another") + cherrypy.tree.mount(Another(), '/another') cherrypy.config.update({'luxuryyacht': 'throatwobblermangrove', - 'db.scheme': r"sqlite///memory", + 'db.scheme': r'sqlite///memory', }) @@ -161,7 +161,7 @@ class ConfigTests(helper.CPWebCase): ('/another/', 'foo', 'None'), ] for path, key, expected in tests: - self.getPage(path + "?key=" + key) + self.getPage(path + '?key=' + key) self.assertBody(expected) expectedconf = { @@ -183,65 +183,65 @@ class ConfigTests(helper.CPWebCase): 'bax': 'this4', } for key, expected in expectedconf.items(): - self.getPage("/foo/bar?key=" + key) + self.getPage('/foo/bar?key=' + key) self.assertBody(repr(expected)) def testUnrepr(self): - self.getPage("/repr?key=neg") - self.assertBody("-1234") + self.getPage('/repr?key=neg') + self.assertBody('-1234') - self.getPage("/repr?key=filename") - self.assertBody(repr(os.path.join(sys.prefix, "hello.py"))) + self.getPage('/repr?key=filename') + self.assertBody(repr(os.path.join(sys.prefix, 'hello.py'))) - self.getPage("/repr?key=thing1") + self.getPage('/repr?key=thing1') self.assertBody(repr(cherrypy.lib.httputil.response_codes[404])) - if not getattr(cherrypy.server, "using_apache", False): + if not getattr(cherrypy.server, 'using_apache', False): # The object ID's won't match up when using Apache, since the # server and client are running in different processes. - self.getPage("/repr?key=thing2") + self.getPage('/repr?key=thing2') from cherrypy.tutorial import thing2 self.assertBody(repr(thing2)) if not six.PY3: - self.getPage("/repr?key=thing3") + self.getPage('/repr?key=thing3') self.assertBody(repr(unicode('test'))) - self.getPage("/repr?key=complex") - self.assertBody("(3+2j)") + self.getPage('/repr?key=complex') + self.assertBody('(3+2j)') - self.getPage("/repr?key=mul") - self.assertBody("18") + self.getPage('/repr?key=mul') + self.assertBody('18') - self.getPage("/repr?key=stradd") - self.assertBody(repr("112233")) + self.getPage('/repr?key=stradd') + self.assertBody(repr('112233')) def testRespNamespaces(self): - self.getPage("/foo/silly") + self.getPage('/foo/silly') self.assertHeader('X-silly', 'sillyval') self.assertBody('Hello world') def testCustomNamespaces(self): - self.getPage("/raw/incr?num=12") - self.assertBody("13") + self.getPage('/raw/incr?num=12') + self.assertBody('13') - self.getPage("/dbscheme") - self.assertBody(r"sqlite///memory") + self.getPage('/dbscheme') + self.assertBody(r'sqlite///memory') def testHandlerToolConfigOverride(self): # Assert that config overrides tool constructor args. Above, we set # the favicon in the page handler to be '../favicon.ico', # but then overrode it in config to be './static/dirback.jpg'. - self.getPage("/favicon.ico") - self.assertBody(open(os.path.join(localDir, "static/dirback.jpg"), - "rb").read()) + self.getPage('/favicon.ico') + self.assertBody(open(os.path.join(localDir, 'static/dirback.jpg'), + 'rb').read()) def test_request_body_namespace(self): - self.getPage("/plain", method='POST', headers=[ + self.getPage('/plain', method='POST', headers=[ ('Content-Type', 'application/x-www-form-urlencoded'), ('Content-Length', '13')], body=compat.ntob('\xff\xfex\x00=\xff\xfea\x00b\x00c\x00')) - self.assertBody("abc") + self.assertBody('abc') class VariableSubstitutionTests(unittest.TestCase): @@ -265,9 +265,9 @@ class VariableSubstitutionTests(unittest.TestCase): fp = StringIOFromNative(conf) cherrypy.config.update(fp) - self.assertEqual(cherrypy.config["my"]["my.dir"], "/some/dir/my/dir") - self.assertEqual(cherrypy.config["my"] - ["my.dir2"], "/some/dir/my/dir/dir2") + self.assertEqual(cherrypy.config['my']['my.dir'], '/some/dir/my/dir') + self.assertEqual(cherrypy.config['my'] + ['my.dir2'], '/some/dir/my/dir/dir2') class CallablesInConfigTest(unittest.TestCase): @@ -291,9 +291,9 @@ class CallablesInConfigTest(unittest.TestCase): value = dict(foo="buzz", **cherrypy._test_dict) """) test_dict = { - "foo": "bar", - "bar": "foo", - "fizz": "buzz" + 'foo': 'bar', + 'bar': 'foo', + 'fizz': 'buzz' } cherrypy._test_dict = test_dict fp = StringIOFromNative(conf) diff --git a/cherrypy/test/test_config_server.py b/cherrypy/test/test_config_server.py index 7afc21b0..7b183530 100644 --- a/cherrypy/test/test_config_server.py +++ b/cherrypy/test/test_config_server.py @@ -25,7 +25,7 @@ class ServerConfigTests(helper.CPWebCase): @cherrypy.expose def upload(self, file): - return "Size: %s" % len(file.file.read()) + return 'Size: %s' % len(file.file.read()) @cherrypy.expose @cherrypy.config(**{'request.body.maxbytes': 100}) @@ -53,49 +53,49 @@ class ServerConfigTests(helper.CPWebCase): PORT = 9876 def testBasicConfig(self): - self.getPage("/") + self.getPage('/') self.assertBody(str(self.PORT)) def testAdditionalServers(self): if self.scheme == 'https': - return self.skip("not available under ssl") + return self.skip('not available under ssl') self.PORT = 9877 - self.getPage("/") + self.getPage('/') self.assertBody(str(self.PORT)) self.PORT = 9878 - self.getPage("/") + self.getPage('/') self.assertBody(str(self.PORT)) def testMaxRequestSizePerHandler(self): - if getattr(cherrypy.server, "using_apache", False): - return self.skip("skipped due to known Apache differences... ") + if getattr(cherrypy.server, 'using_apache', False): + return self.skip('skipped due to known Apache differences... ') - self.getPage('/tinyupload', method="POST", + self.getPage('/tinyupload', method='POST', headers=[('Content-Type', 'text/plain'), ('Content-Length', '100')], - body="x" * 100) + body='x' * 100) self.assertStatus(200) - self.assertBody("x" * 100) + self.assertBody('x' * 100) - self.getPage('/tinyupload', method="POST", + self.getPage('/tinyupload', method='POST', headers=[('Content-Type', 'text/plain'), ('Content-Length', '101')], - body="x" * 101) + body='x' * 101) self.assertStatus(413) def testMaxRequestSize(self): - if getattr(cherrypy.server, "using_apache", False): - return self.skip("skipped due to known Apache differences... ") + if getattr(cherrypy.server, 'using_apache', False): + return self.skip('skipped due to known Apache differences... ') for size in (500, 5000, 50000): - self.getPage("/", headers=[('From', "x" * 500)]) + self.getPage('/', headers=[('From', 'x' * 500)]) self.assertStatus(413) # Test for https://github.com/cherrypy/cherrypy/issues/421 # (Incorrect border condition in readline of SizeCheckWrapper). # This hangs in rev 891 and earlier. - lines256 = "x" * 248 - self.getPage("/", + lines256 = 'x' * 248 + self.getPage('/', headers=[('Host', '%s:%s' % (self.HOST, self.PORT)), ('From', lines256)]) @@ -113,14 +113,14 @@ class ServerConfigTests(helper.CPWebCase): '%s', '--x--']) partlen = 200 - len(body) - b = body % ("x" * partlen) - h = [("Content-type", "multipart/form-data; boundary=x"), - ("Content-Length", "%s" % len(b))] - self.getPage('/upload', h, "POST", b) + b = body % ('x' * partlen) + h = [('Content-type', 'multipart/form-data; boundary=x'), + ('Content-Length', '%s' % len(b))] + self.getPage('/upload', h, 'POST', b) self.assertBody('Size: %d' % partlen) - b = body % ("x" * 200) - h = [("Content-type", "multipart/form-data; boundary=x"), - ("Content-Length", "%s" % len(b))] - self.getPage('/upload', h, "POST", b) + b = body % ('x' * 200) + h = [('Content-type', 'multipart/form-data; boundary=x'), + ('Content-Length', '%s' % len(b))] + self.getPage('/upload', h, 'POST', b) self.assertStatus(413) diff --git a/cherrypy/test/test_conn.py b/cherrypy/test/test_conn.py index 1382c9e0..f7ce10cd 100644 --- a/cherrypy/test/test_conn.py +++ b/cherrypy/test/test_conn.py @@ -37,7 +37,7 @@ def setup_server(): @cherrypy.expose def hello(self): - return "Hello, world!" + return 'Hello, world!' @cherrypy.expose def timeout(self, t): @@ -69,16 +69,16 @@ def setup_server(): @cherrypy.expose def custom(self, response_code): cherrypy.response.status = response_code - return "Code = %s" % response_code + return 'Code = %s' % response_code @cherrypy.expose @cherrypy.config(**{'hooks.on_start_resource': raise500}) def err_before_read(self): - return "ok" + return 'ok' @cherrypy.expose def one_megabyte_of_a(self): - return ["a" * 1024] * 1024 + return ['a' * 1024] * 1024 @cherrypy.expose # Turn off the encoding tool so it doens't collapse @@ -106,33 +106,33 @@ class ConnectionCloseTests(helper.CPWebCase): setup_server = staticmethod(setup_server) def test_HTTP11(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' self.persistent = True # Make the first request and assert there's no "Connection: close". - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertBody(pov) - self.assertNoHeader("Connection") + self.assertNoHeader('Connection') # Make another request on the same connection. - self.getPage("/page1") + self.getPage('/page1') self.assertStatus('200 OK') self.assertBody(pov) - self.assertNoHeader("Connection") + self.assertNoHeader('Connection') # Test client-side close. - self.getPage("/page2", headers=[("Connection", "close")]) + self.getPage('/page2', headers=[('Connection', 'close')]) self.assertStatus('200 OK') self.assertBody(pov) - self.assertHeader("Connection", "close") + self.assertHeader('Connection', 'close') # Make another request on the same connection, which should error. - self.assertRaises(NotConnected, self.getPage, "/") + self.assertRaises(NotConnected, self.getPage, '/') def test_Streaming_no_len(self): try: @@ -153,25 +153,25 @@ class ConnectionCloseTests(helper.CPWebCase): pass def _streaming(self, set_cl): - if cherrypy.server.protocol_version == "HTTP/1.1": - self.PROTOCOL = "HTTP/1.1" + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.PROTOCOL = 'HTTP/1.1' self.persistent = True # Make the first request and assert there's no "Connection: close". - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertBody(pov) - self.assertNoHeader("Connection") + self.assertNoHeader('Connection') # Make another, streamed request on the same connection. if set_cl: # When a Content-Length is provided, the content should stream # without closing the connection. - self.getPage("/stream?set_cl=Yes") - self.assertHeader("Content-Length") - self.assertNoHeader("Connection", "close") - self.assertNoHeader("Transfer-Encoding") + self.getPage('/stream?set_cl=Yes') + self.assertHeader('Content-Length') + self.assertNoHeader('Connection', 'close') + self.assertNoHeader('Transfer-Encoding') self.assertStatus('200 OK') self.assertBody('0123456789') @@ -179,78 +179,78 @@ class ConnectionCloseTests(helper.CPWebCase): # When no Content-Length response header is provided, # streamed output will either close the connection, or use # chunked encoding, to determine transfer-length. - self.getPage("/stream") - self.assertNoHeader("Content-Length") + self.getPage('/stream') + self.assertNoHeader('Content-Length') self.assertStatus('200 OK') self.assertBody('0123456789') chunked_response = False for k, v in self.headers: - if k.lower() == "transfer-encoding": - if str(v) == "chunked": + if k.lower() == 'transfer-encoding': + if str(v) == 'chunked': chunked_response = True if chunked_response: - self.assertNoHeader("Connection", "close") + self.assertNoHeader('Connection', 'close') else: - self.assertHeader("Connection", "close") + self.assertHeader('Connection', 'close') # Make another request on the same connection, which should # error. - self.assertRaises(NotConnected, self.getPage, "/") + self.assertRaises(NotConnected, self.getPage, '/') # Try HEAD. See # https://github.com/cherrypy/cherrypy/issues/864. - self.getPage("/stream", method='HEAD') + self.getPage('/stream', method='HEAD') self.assertStatus('200 OK') self.assertBody('') - self.assertNoHeader("Transfer-Encoding") + self.assertNoHeader('Transfer-Encoding') else: - self.PROTOCOL = "HTTP/1.0" + self.PROTOCOL = 'HTTP/1.0' self.persistent = True # Make the first request and assert Keep-Alive. - self.getPage("/", headers=[("Connection", "Keep-Alive")]) + self.getPage('/', headers=[('Connection', 'Keep-Alive')]) self.assertStatus('200 OK') self.assertBody(pov) - self.assertHeader("Connection", "Keep-Alive") + self.assertHeader('Connection', 'Keep-Alive') # Make another, streamed request on the same connection. if set_cl: # When a Content-Length is provided, the content should # stream without closing the connection. - self.getPage("/stream?set_cl=Yes", - headers=[("Connection", "Keep-Alive")]) - self.assertHeader("Content-Length") - self.assertHeader("Connection", "Keep-Alive") - self.assertNoHeader("Transfer-Encoding") + self.getPage('/stream?set_cl=Yes', + headers=[('Connection', 'Keep-Alive')]) + self.assertHeader('Content-Length') + self.assertHeader('Connection', 'Keep-Alive') + self.assertNoHeader('Transfer-Encoding') self.assertStatus('200 OK') self.assertBody('0123456789') else: # When a Content-Length is not provided, # the server should close the connection. - self.getPage("/stream", headers=[("Connection", "Keep-Alive")]) + self.getPage('/stream', headers=[('Connection', 'Keep-Alive')]) self.assertStatus('200 OK') self.assertBody('0123456789') - self.assertNoHeader("Content-Length") - self.assertNoHeader("Connection", "Keep-Alive") - self.assertNoHeader("Transfer-Encoding") + self.assertNoHeader('Content-Length') + self.assertNoHeader('Connection', 'Keep-Alive') + self.assertNoHeader('Transfer-Encoding') # Make another request on the same connection, which should # error. - self.assertRaises(NotConnected, self.getPage, "/") + self.assertRaises(NotConnected, self.getPage, '/') def test_HTTP10_KeepAlive(self): - self.PROTOCOL = "HTTP/1.0" - if self.scheme == "https": + self.PROTOCOL = 'HTTP/1.0' + if self.scheme == 'https': self.HTTP_CONN = HTTPSConnection else: self.HTTP_CONN = HTTPConnection # Test a normal HTTP/1.0 request. - self.getPage("/page2") + self.getPage('/page2') self.assertStatus('200 OK') self.assertBody(pov) # Apache, for example, may emit a Connection header even for HTTP/1.0 @@ -259,13 +259,13 @@ class ConnectionCloseTests(helper.CPWebCase): # Test a keep-alive HTTP/1.0 request. self.persistent = True - self.getPage("/page3", headers=[("Connection", "Keep-Alive")]) + self.getPage('/page3', headers=[('Connection', 'Keep-Alive')]) self.assertStatus('200 OK') self.assertBody(pov) - self.assertHeader("Connection", "Keep-Alive") + self.assertHeader('Connection', 'Keep-Alive') # Remove the keep-alive header again. - self.getPage("/page3") + self.getPage('/page3') self.assertStatus('200 OK') self.assertBody(pov) # Apache, for example, may emit a Connection header even for HTTP/1.0 @@ -278,10 +278,10 @@ class PipelineTests(helper.CPWebCase): def test_HTTP11_Timeout(self): # If we timeout without sending any data, # the server will close the conn with a 408. - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Connect but send nothing. self.persistent = True @@ -293,7 +293,7 @@ class PipelineTests(helper.CPWebCase): time.sleep(timeout * 2) # The request should have returned 408 already. - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 408) conn.close() @@ -304,13 +304,13 @@ class PipelineTests(helper.CPWebCase): conn.auto_open = False conn.connect() conn.send(ntob('GET /hello HTTP/1.1')) - conn.send(("Host: %s" % self.HOST).encode('ascii')) + conn.send(('Host: %s' % self.HOST).encode('ascii')) # Wait for our socket timeout time.sleep(timeout * 2) # The conn should have already sent 408. - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 408) conn.close() @@ -318,18 +318,18 @@ class PipelineTests(helper.CPWebCase): def test_HTTP11_Timeout_after_request(self): # If we timeout after at least one request has succeeded, # the server will close the conn without 408. - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Make an initial request self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/timeout?t=%s" % timeout, skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/timeout?t=%s' % timeout, skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() @@ -337,33 +337,33 @@ class PipelineTests(helper.CPWebCase): # Make a second request on the same socket conn._output(ntob('GET /hello HTTP/1.1')) - conn._output(ntob("Host: %s" % self.HOST, 'ascii')) + conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() - self.assertBody("Hello, world!") + self.assertBody('Hello, world!') # Wait for our socket timeout time.sleep(timeout * 2) # Make another request on the same socket, which should error conn._output(ntob('GET /hello HTTP/1.1')) - conn._output(ntob("Host: %s" % self.HOST, 'ascii')) + conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') try: response.begin() except: if not isinstance(sys.exc_info()[1], (socket.error, BadStatusLine)): self.fail("Writing to timed out socket didn't fail" - " as it should have: %s" % sys.exc_info()[1]) + ' as it should have: %s' % sys.exc_info()[1]) else: if response.status != 408: self.fail("Writing to timed out socket didn't fail" - " as it should have: %s" % + ' as it should have: %s' % response.read()) conn.close() @@ -371,10 +371,10 @@ class PipelineTests(helper.CPWebCase): # Make another request on a new socket, which should work self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() @@ -385,17 +385,17 @@ class PipelineTests(helper.CPWebCase): conn.send(ntob('GET /hello HTTP/1.1')) # Wait for our socket timeout time.sleep(timeout * 2) - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') try: response.begin() except: if not isinstance(sys.exc_info()[1], (socket.error, BadStatusLine)): self.fail("Writing to timed out socket didn't fail" - " as it should have: %s" % sys.exc_info()[1]) + ' as it should have: %s' % sys.exc_info()[1]) else: self.fail("Writing to timed out socket didn't fail" - " as it should have: %s" % + ' as it should have: %s' % response.read()) conn.close() @@ -403,10 +403,10 @@ class PipelineTests(helper.CPWebCase): # Retry the request on a new connection, which should work self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) self.body = response.read() @@ -414,53 +414,53 @@ class PipelineTests(helper.CPWebCase): conn.close() def test_HTTP11_pipelining(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Test pipelining. httplib doesn't support this directly. self.persistent = True conn = self.HTTP_CONN # Put request 1 - conn.putrequest("GET", "/hello", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/hello', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() for trial in range(5): # Put next request conn._output(ntob('GET /hello HTTP/1.1')) - conn._output(ntob("Host: %s" % self.HOST, 'ascii')) + conn._output(ntob('Host: %s' % self.HOST, 'ascii')) conn._send_output() # Retrieve previous response - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') # there is a bug in python3 regarding the buffering of # ``conn.sock``. Until that bug get's fixed we will # monkey patch the ``reponse`` 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) - self.assertEqual(body, ntob("Hello, world!")) + self.assertEqual(body, ntob('Hello, world!')) # Retrieve final response - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() body = response.read() self.assertEqual(response.status, 200) - self.assertEqual(body, ntob("Hello, world!")) + self.assertEqual(body, ntob('Hello, world!')) conn.close() def test_100_Continue(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' self.persistent = True conn = self.HTTP_CONN @@ -469,13 +469,13 @@ class PipelineTests(helper.CPWebCase): # Note that httplib's response.begin automatically ignores # 100 Continue responses, so we must manually check for it. try: - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Content-Type", "text/plain") - conn.putheader("Content-Length", "4") + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Content-Type', 'text/plain') + conn.putheader('Content-Length', '4') conn.endheaders() conn.send(ntob("d'oh")) - response = conn.response_class(conn.sock, method="POST") + response = conn.response_class(conn.sock, method='POST') version, status, reason = response._read_status() self.assertNotEqual(status, 100) finally: @@ -484,13 +484,13 @@ class PipelineTests(helper.CPWebCase): # Now try a page with an Expect header... try: conn.connect() - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Content-Type", "text/plain") - conn.putheader("Content-Length", "17") - conn.putheader("Expect", "100-continue") + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Content-Type', 'text/plain') + conn.putheader('Content-Length', '17') + conn.putheader('Expect', '100-continue') conn.endheaders() - response = conn.response_class(conn.sock, method="POST") + response = conn.response_class(conn.sock, method='POST') # ...assert and then skip the 100 response version, status, reason = response._read_status() @@ -499,13 +499,13 @@ class PipelineTests(helper.CPWebCase): line = response.fp.readline().strip() if line: self.fail( - "100 Continue should not output any headers. Got %r" % + '100 Continue should not output any headers. Got %r' % line) else: break # ...send the body - body = ntob("I am a small file") + body = ntob('I am a small file') conn.send(body) # ...get the final response @@ -521,12 +521,12 @@ class ConnectionTests(helper.CPWebCase): setup_server = staticmethod(setup_server) def test_readall_or_close(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' - if self.scheme == "https": + if self.scheme == 'https': self.HTTP_CONN = HTTPSConnection else: self.HTTP_CONN = HTTPConnection @@ -540,13 +540,13 @@ class ConnectionTests(helper.CPWebCase): conn = self.HTTP_CONN # Get a POST page with an error - conn.putrequest("POST", "/err_before_read", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Content-Type", "text/plain") - conn.putheader("Content-Length", "1000") - conn.putheader("Expect", "100-continue") + conn.putrequest('POST', '/err_before_read', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Content-Type', 'text/plain') + conn.putheader('Content-Length', '1000') + conn.putheader('Expect', '100-continue') conn.endheaders() - response = conn.response_class(conn.sock, method="POST") + response = conn.response_class(conn.sock, method='POST') # ...assert and then skip the 100 response version, status, reason = response._read_status() @@ -557,7 +557,7 @@ class ConnectionTests(helper.CPWebCase): break # ...send the body - conn.send(ntob("x" * 1000)) + conn.send(ntob('x' * 1000)) # ...get the final response response.begin() @@ -566,12 +566,12 @@ class ConnectionTests(helper.CPWebCase): # Now try a working page with an Expect header... conn._output(ntob('POST /upload HTTP/1.1')) - conn._output(ntob("Host: %s" % self.HOST, 'ascii')) - conn._output(ntob("Content-Type: text/plain")) - conn._output(ntob("Content-Length: 17")) - conn._output(ntob("Expect: 100-continue")) + conn._output(ntob('Host: %s' % self.HOST, 'ascii')) + conn._output(ntob('Content-Type: text/plain')) + conn._output(ntob('Content-Length: 17')) + conn._output(ntob('Expect: 100-continue')) conn._send_output() - response = conn.response_class(conn.sock, method="POST") + response = conn.response_class(conn.sock, method='POST') # ...assert and then skip the 100 response version, status, reason = response._read_status() @@ -582,7 +582,7 @@ class ConnectionTests(helper.CPWebCase): break # ...send the body - body = ntob("I am a small file") + body = ntob('I am a small file') conn.send(body) # ...get the final response @@ -593,61 +593,61 @@ class ConnectionTests(helper.CPWebCase): conn.close() def test_No_Message_Body(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Set our HTTP_CONN to an instance so it persists between requests. self.persistent = True # Make the first request and assert there's no "Connection: close". - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertBody(pov) - self.assertNoHeader("Connection") + self.assertNoHeader('Connection') # Make a 204 request on the same connection. - self.getPage("/custom/204") + self.getPage('/custom/204') self.assertStatus(204) - self.assertNoHeader("Content-Length") - self.assertBody("") - self.assertNoHeader("Connection") + self.assertNoHeader('Content-Length') + self.assertBody('') + self.assertNoHeader('Connection') # Make a 304 request on the same connection. - self.getPage("/custom/304") + self.getPage('/custom/304') self.assertStatus(304) - self.assertNoHeader("Content-Length") - self.assertBody("") - self.assertNoHeader("Connection") + self.assertNoHeader('Content-Length') + self.assertBody('') + self.assertNoHeader('Connection') def test_Chunked_Encoding(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() if (hasattr(self, 'harness') and - "modpython" in self.harness.__class__.__name__.lower()): + 'modpython' in self.harness.__class__.__name__.lower()): # mod_python forbids chunked encoding return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Set our HTTP_CONN to an instance so it persists between requests. self.persistent = True conn = self.HTTP_CONN # Try a normal chunked request (with extensions) - body = ntob("8;key=value\r\nxx\r\nxxxx\r\n5\r\nyyyyy\r\n0\r\n" - "Content-Type: application/json\r\n" - "\r\n") - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Transfer-Encoding", "chunked") - conn.putheader("Trailer", "Content-Type") + body = ntob('8;key=value\r\nxx\r\nxxxx\r\n5\r\nyyyyy\r\n0\r\n' + 'Content-Type: application/json\r\n' + '\r\n') + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Transfer-Encoding', 'chunked') + conn.putheader('Trailer', 'Content-Type') # Note that this is somewhat malformed: # we shouldn't be sending Content-Length. # RFC 2616 says the server should ignore it. - conn.putheader("Content-Length", "3") + conn.putheader('Content-Length', '3') conn.endheaders() conn.send(body) response = conn.getresponse() @@ -657,11 +657,11 @@ class ConnectionTests(helper.CPWebCase): # Try a chunked request that exceeds server.max_request_body_size. # Note that the delimiters and trailer are included. - body = ntob("3e3\r\n" + ("x" * 995) + "\r\n0\r\n\r\n") - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Transfer-Encoding", "chunked") - conn.putheader("Content-Type", "text/plain") + body = ntob('3e3\r\n' + ('x' * 995) + '\r\n0\r\n\r\n') + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Transfer-Encoding', 'chunked') + conn.putheader('Content-Type', 'text/plain') # Chunked requests don't need a content-length ## conn.putheader("Content-Length", len(body)) conn.endheaders() @@ -676,16 +676,16 @@ class ConnectionTests(helper.CPWebCase): # server.max_request_body_size. Assert error before body send. self.persistent = True conn = self.HTTP_CONN - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Content-Type", "text/plain") - conn.putheader("Content-Length", "9999") + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Content-Type', 'text/plain') + conn.putheader('Content-Length', '9999') conn.endheaders() response = conn.getresponse() self.status, self.headers, self.body = webtest.shb(response) self.assertStatus(413) - self.assertBody("The entity sent with the request exceeds " - "the maximum allowed bytes.") + self.assertBody('The entity sent with the request exceeds ' + 'the maximum allowed bytes.') conn.close() def test_Content_Length_out_preheaders(self): @@ -693,16 +693,16 @@ class ConnectionTests(helper.CPWebCase): # the actual bytes in the response body. self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/custom_cl?body=I+have+too+many+bytes&cl=5", + conn.putrequest('GET', '/custom_cl?body=I+have+too+many+bytes&cl=5', skip_host=True) - conn.putheader("Host", self.HOST) + conn.putheader('Host', self.HOST) conn.endheaders() response = conn.getresponse() self.status, self.headers, self.body = webtest.shb(response) self.assertStatus(500) self.assertBody( - "The requested resource returned more bytes than the " - "declared Content-Length.") + 'The requested resource returned more bytes than the ' + 'declared Content-Length.') conn.close() def test_Content_Length_out_postheaders(self): @@ -711,14 +711,14 @@ class ConnectionTests(helper.CPWebCase): self.persistent = True conn = self.HTTP_CONN conn.putrequest( - "GET", "/custom_cl?body=I+too&body=+have+too+many&cl=5", + 'GET', '/custom_cl?body=I+too&body=+have+too+many&cl=5', skip_host=True) - conn.putheader("Host", self.HOST) + conn.putheader('Host', self.HOST) conn.endheaders() response = conn.getresponse() self.status, self.headers, self.body = webtest.shb(response) self.assertStatus(200) - self.assertBody("I too") + self.assertBody('I too') conn.close() def test_598(self): @@ -736,7 +736,7 @@ class ConnectionTests(helper.CPWebCase): remaining -= len(data) self.assertEqual(len(buf), 1024 * 1024) - self.assertEqual(buf, ntob("a" * 1024 * 1024)) + self.assertEqual(buf, ntob('a' * 1024 * 1024)) self.assertEqual(remaining, 0) remote_data_conn.close() @@ -765,12 +765,12 @@ socket_reset_errors = [ for name in reset_names if hasattr(errno, name) ] -"reset error numbers available on this platform" +'reset error numbers available on this platform' socket_reset_errors += [ # Python 3.5 raises an http.client.RemoteDisconnected # with this message - "Remote end closed connection without response", + 'Remote end closed connection without response', ] @@ -786,10 +786,10 @@ class LimitedRequestQueueTests(helper.CPWebCase): # all of wsgiserver's WorkerThreads and fill its Queue. for i in range(15): conn = self.HTTP_CONN(self.HOST, self.PORT) - conn.putrequest("POST", "/upload", skip_host=True) - conn.putheader("Host", self.HOST) - conn.putheader("Content-Type", "text/plain") - conn.putheader("Content-Length", "4") + conn.putrequest('POST', '/upload', skip_host=True) + conn.putheader('Host', self.HOST) + conn.putheader('Content-Type', 'text/plain') + conn.putheader('Content-Length', '4') conn.endheaders() conns.append(conn) @@ -804,10 +804,10 @@ class LimitedRequestQueueTests(helper.CPWebCase): overflow_conn.sock.connect(sa) break - overflow_conn.putrequest("GET", "/", skip_host=True) - overflow_conn.putheader("Host", self.HOST) + overflow_conn.putrequest('GET', '/', skip_host=True) + overflow_conn.putheader('Host', self.HOST) overflow_conn.endheaders() - response = overflow_conn.response_class(overflow_conn.sock, method="GET") + response = overflow_conn.response_class(overflow_conn.sock, method='GET') try: response.begin() except socket.error as exc: @@ -815,8 +815,8 @@ class LimitedRequestQueueTests(helper.CPWebCase): pass # Expected. else: tmpl = ( - "Overflow conn did not get RST. " - "Got {exc.args!r} instead" + 'Overflow conn did not get RST. ' + 'Got {exc.args!r} instead' ) raise AssertionError(tmpl.format(**locals())) except BadStatusLine: @@ -824,11 +824,11 @@ class LimitedRequestQueueTests(helper.CPWebCase): # RST correctly. assert sys.platform == 'darwin' else: - raise AssertionError("Overflow conn did not get RST ") + raise AssertionError('Overflow conn did not get RST ') finally: for conn in conns: - conn.send(ntob("done")) - response = conn.response_class(conn.sock, method="POST") + conn.send(ntob('done')) + response = conn.response_class(conn.sock, method='POST') response.begin() self.body = response.read() self.assertBody("thanks for 'done'") @@ -845,16 +845,16 @@ class BadRequestTests(helper.CPWebCase): conn = self.HTTP_CONN conn.send(ntob('GET /hello HTTP/1.1\n\n')) - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.body = response.read() - self.assertBody("HTTP requires CRLF terminators") + self.assertBody('HTTP requires CRLF terminators') conn.close() conn.connect() conn.send(ntob('GET /hello HTTP/1.1\r\n\n')) - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.body = response.read() - self.assertBody("HTTP requires CRLF terminators") + self.assertBody('HTTP requires CRLF terminators') conn.close() diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index fae1c27c..0140bef4 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -16,7 +16,7 @@ from cherrypy.test import helper localDir = os.path.dirname(__file__) -favicon_path = os.path.join(os.getcwd(), localDir, "../favicon.ico") +favicon_path = os.path.join(os.getcwd(), localDir, '../favicon.ico') # Client-side code # @@ -29,13 +29,13 @@ class CoreRequestHandlingTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "hello" + return 'hello' favicon_ico = tools.staticfile.handler(filename=favicon_path) @cherrypy.expose def defct(self, newct): - newct = "text/%s" % newct + newct = 'text/%s' % newct cherrypy.config.update({'tools.response_headers.on': True, 'tools.response_headers.headers': [('Content-Type', newct)]}) @@ -82,10 +82,10 @@ class CoreRequestHandlingTest(helper.CPWebCase): class Status(Test): def index(self): - return "normal" + return 'normal' def blank(self): - cherrypy.response.status = "" + cherrypy.response.status = '' # According to RFC 2616, new status codes are OK as long as they # are between 100 and 599. @@ -93,17 +93,17 @@ class CoreRequestHandlingTest(helper.CPWebCase): # Here is an illegal code... def illegal(self): cherrypy.response.status = 781 - return "oops" + return 'oops' # ...and here is an unknown but legal code. def unknown(self): - cherrypy.response.status = "431 My custom error" - return "funky" + cherrypy.response.status = '431 My custom error' + return 'funky' # Non-numeric code def bad(self): - cherrypy.response.status = "error" - return "bad news" + cherrypy.response.status = 'error' + return 'bad news' statuses = [] @@ -114,57 +114,57 @@ class CoreRequestHandlingTest(helper.CPWebCase): class Redirect(Test): @cherrypy.config(**{ - "tools.err_redirect.on": True, - "tools.err_redirect.url": "/errpage", - "tools.err_redirect.internal": False, + 'tools.err_redirect.on': True, + 'tools.err_redirect.url': '/errpage', + 'tools.err_redirect.internal': False, }) class Error: @cherrypy.expose def index(self): - raise NameError("redirect_test") + raise NameError('redirect_test') error = Error() def index(self): - return "child" + return 'child' def custom(self, url, code): raise cherrypy.HTTPRedirect(url, code) @cherrypy.config(**{'tools.trailing_slash.extra': True}) def by_code(self, code): - raise cherrypy.HTTPRedirect("somewhere%20else", code) + raise cherrypy.HTTPRedirect('somewhere%20else', code) def nomodify(self): - raise cherrypy.HTTPRedirect("", 304) + raise cherrypy.HTTPRedirect('', 304) def proxy(self): - raise cherrypy.HTTPRedirect("proxy", 305) + raise cherrypy.HTTPRedirect('proxy', 305) def stringify(self): - return str(cherrypy.HTTPRedirect("/")) + return str(cherrypy.HTTPRedirect('/')) def fragment(self, frag): - raise cherrypy.HTTPRedirect("/some/url#%s" % frag) + raise cherrypy.HTTPRedirect('/some/url#%s' % frag) def url_with_quote(self): raise cherrypy.HTTPRedirect("/some\"url/that'we/want") def url_with_unicode(self): - raise cherrypy.HTTPRedirect(ntou("тест", "utf-8")) + raise cherrypy.HTTPRedirect(ntou('тест', 'utf-8')) def login_redir(): - if not getattr(cherrypy.request, "login", None): - raise cherrypy.InternalRedirect("/internalredirect/login") + if not getattr(cherrypy.request, 'login', None): + raise cherrypy.InternalRedirect('/internalredirect/login') tools.login_redir = _cptools.Tool('before_handler', login_redir) def redir_custom(): - raise cherrypy.InternalRedirect("/internalredirect/custom_err") + raise cherrypy.InternalRedirect('/internalredirect/custom_err') class InternalRedirect(Test): def index(self): - raise cherrypy.InternalRedirect("/") + raise cherrypy.InternalRedirect('/') @cherrypy.expose @cherrypy.config(**{'hooks.before_error_response': redir_custom}) @@ -172,18 +172,18 @@ class CoreRequestHandlingTest(helper.CPWebCase): return 3 / 0 def relative(self, a, b): - raise cherrypy.InternalRedirect("cousin?t=6") + raise cherrypy.InternalRedirect('cousin?t=6') def cousin(self, t): assert cherrypy.request.prev.closed return cherrypy.request.prev.query_string def petshop(self, user_id): - if user_id == "parrot": + if user_id == 'parrot': # Trade it for a slug when redirecting raise cherrypy.InternalRedirect( '/image/getImagesByUser?user_id=slug') - elif user_id == "terrier": + elif user_id == 'terrier': # Trade it for a fish when redirecting raise cherrypy.InternalRedirect( '/image/getImagesByUser?user_id=fish') @@ -196,37 +196,37 @@ class CoreRequestHandlingTest(helper.CPWebCase): # this: # @tools.login_redir() def secure(self): - return "Welcome!" + return 'Welcome!' secure = tools.login_redir()(secure) # Since calling the tool returns the same function you pass in, # you could skip binding the return value, and just write: # tools.login_redir()(secure) def login(self): - return "Please log in" + return 'Please log in' def custom_err(self): - return "Something went horribly wrong." + return 'Something went horribly wrong.' @cherrypy.config(**{'hooks.before_request_body': redir_custom}) def early_ir(self, arg): - return "whatever" + return 'whatever' class Image(Test): def getImagesByUser(self, user_id): - return "0 images for %s" % user_id + return '0 images for %s' % user_id class Flatten(Test): def as_string(self): - return "content" + return 'content' def as_list(self): - return ["con", "tent"] + return ['con', 'tent'] def as_yield(self): - yield ntob("content") + yield ntob('content') @cherrypy.config(**{'tools.flatten.on': True}) def as_dblyield(self): @@ -244,7 +244,7 @@ class CoreRequestHandlingTest(helper.CPWebCase): def slice_file(self): path = os.path.join(os.getcwd(), os.path.dirname(__file__)) return static.serve_file( - os.path.join(path, "static/index.html")) + os.path.join(path, 'static/index.html')) class Cookies(Test): @@ -259,8 +259,8 @@ class CoreRequestHandlingTest(helper.CPWebCase): def append_headers(header_list, debug=False): if debug: cherrypy.log( - "Extending response headers with %s" % repr(header_list), - "TOOLS.APPEND_HEADERS") + 'Extending response headers with %s' % repr(header_list), + 'TOOLS.APPEND_HEADERS') cherrypy.serving.response.header_list.extend(header_list) cherrypy.tools.append_headers = cherrypy.Tool( 'on_end_resource', append_headers) @@ -281,25 +281,25 @@ class CoreRequestHandlingTest(helper.CPWebCase): cherrypy.tree.mount(root) def testStatus(self): - self.getPage("/status/") + self.getPage('/status/') self.assertBody('normal') self.assertStatus(200) - self.getPage("/status/blank") + self.getPage('/status/blank') self.assertBody('') self.assertStatus(200) - self.getPage("/status/illegal") + self.getPage('/status/illegal') self.assertStatus(500) - msg = "Illegal response status from server (781 is out of range)." + msg = 'Illegal response status from server (781 is out of range).' self.assertErrorPage(500, msg) if not getattr(cherrypy.server, 'using_apache', False): - self.getPage("/status/unknown") + self.getPage('/status/unknown') self.assertBody('funky') self.assertStatus(431) - self.getPage("/status/bad") + self.getPage('/status/bad') self.assertStatus(500) msg = "Illegal response status from server ('error' is non-numeric)." self.assertErrorPage(500, msg) @@ -308,21 +308,21 @@ class CoreRequestHandlingTest(helper.CPWebCase): self.getPage('/status/on_end_resource_stage') self.assertBody('[]') self.getPage('/status/on_end_resource_stage') - self.assertBody(repr(["200 OK"])) + self.assertBody(repr(['200 OK'])) def testSlashes(self): # Test that requests for index methods without a trailing slash # get redirected to the same URI path with a trailing slash. # Make sure GET params are preserved. - self.getPage("/redirect?id=3") + self.getPage('/redirect?id=3') self.assertStatus(301) self.assertMatchesBody('<a href=([\'"])%s/redirect/[?]id=3\\1>' - "%s/redirect/[?]id=3</a>" % (self.base(), self.base())) + '%s/redirect/[?]id=3</a>' % (self.base(), self.base())) if self.prefix(): # Corner case: the "trailing slash" redirect could be tricky if # we're using a virtual root and the URI is "/vroot" (no slash). - self.getPage("") + self.getPage('') self.assertStatus(301) self.assertMatchesBody("<a href=(['\"])%s/\\1>%s/</a>" % (self.base(), self.base())) @@ -330,10 +330,10 @@ class CoreRequestHandlingTest(helper.CPWebCase): # Test that requests for NON-index methods WITH a trailing slash # get redirected to the same URI path WITHOUT a trailing slash. # Make sure GET params are preserved. - self.getPage("/redirect/by_code/?code=307") + self.getPage('/redirect/by_code/?code=307') self.assertStatus(301) self.assertMatchesBody("<a href=(['\"])%s/redirect/by_code[?]code=307\\1>" - "%s/redirect/by_code[?]code=307</a>" + '%s/redirect/by_code[?]code=307</a>' % (self.base(), self.base())) # If the trailing_slash tool is off, CP should just continue @@ -345,73 +345,73 @@ class CoreRequestHandlingTest(helper.CPWebCase): self.assertBody('%s/url/page1' % self.base()) def testRedirect(self): - self.getPage("/redirect/") + self.getPage('/redirect/') self.assertBody('child') self.assertStatus(200) - self.getPage("/redirect/by_code?code=300") + self.getPage('/redirect/by_code?code=300') self.assertMatchesBody( r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>") self.assertStatus(300) - self.getPage("/redirect/by_code?code=301") + self.getPage('/redirect/by_code?code=301') self.assertMatchesBody( r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>") self.assertStatus(301) - self.getPage("/redirect/by_code?code=302") + self.getPage('/redirect/by_code?code=302') self.assertMatchesBody( r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>") self.assertStatus(302) - self.getPage("/redirect/by_code?code=303") + self.getPage('/redirect/by_code?code=303') self.assertMatchesBody( r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>") self.assertStatus(303) - self.getPage("/redirect/by_code?code=307") + self.getPage('/redirect/by_code?code=307') self.assertMatchesBody( r"<a href=(['\"])(.*)somewhere%20else\1>\2somewhere%20else</a>") self.assertStatus(307) - self.getPage("/redirect/nomodify") + self.getPage('/redirect/nomodify') self.assertBody('') self.assertStatus(304) - self.getPage("/redirect/proxy") + self.getPage('/redirect/proxy') self.assertBody('') self.assertStatus(305) # HTTPRedirect on error - self.getPage("/redirect/error/") + self.getPage('/redirect/error/') self.assertStatus(('302 Found', '303 See Other')) self.assertInBody('/errpage') # Make sure str(HTTPRedirect()) works. - self.getPage("/redirect/stringify", protocol="HTTP/1.0") + self.getPage('/redirect/stringify', protocol='HTTP/1.0') self.assertStatus(200) self.assertBody("(['%s/'], 302)" % self.base()) - if cherrypy.server.protocol_version == "HTTP/1.1": - self.getPage("/redirect/stringify", protocol="HTTP/1.1") + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.getPage('/redirect/stringify', protocol='HTTP/1.1') self.assertStatus(200) self.assertBody("(['%s/'], 303)" % self.base()) # check that #fragments are handled properly # http://skrb.org/ietf/http_errata.html#location-fragments - frag = "foo" - self.getPage("/redirect/fragment/%s" % frag) + frag = 'foo' + self.getPage('/redirect/fragment/%s' % frag) self.assertMatchesBody( r"<a href=(['\"])(.*)\/some\/url\#%s\1>\2\/some\/url\#%s</a>" % ( frag, frag)) loc = self.assertHeader('Location') - assert loc.endswith("#%s" % frag) + assert loc.endswith('#%s' % frag) self.assertStatus(('302 Found', '303 See Other')) # check injection protection # See https://github.com/cherrypy/cherrypy/issues/1003 self.getPage( - "/redirect/custom?" - "code=303&url=/foobar/%0d%0aSet-Cookie:%20somecookie=someval") + '/redirect/custom?' + 'code=303&url=/foobar/%0d%0aSet-Cookie:%20somecookie=someval') self.assertStatus(303) loc = self.assertHeader('Location') assert 'Set-Cookie' in loc @@ -427,12 +427,12 @@ class CoreRequestHandlingTest(helper.CPWebCase): # check redirects to URLs generated valid HTML - we check this # by seeing if it appears as valid XHTML. - self.getPage("/redirect/by_code?code=303") + self.getPage('/redirect/by_code?code=303') self.assertStatus(303) assertValidXHTML() # do the same with a url containing quote characters. - self.getPage("/redirect/url_with_quote") + self.getPage('/redirect/url_with_quote') self.assertStatus(303) assertValidXHTML() @@ -443,126 +443,126 @@ class CoreRequestHandlingTest(helper.CPWebCase): """ # test disabled due to #1440 return - self.getPage("/redirect/url_with_unicode") + self.getPage('/redirect/url_with_unicode') self.assertStatus(303) loc = self.assertHeader('Location') assert ntou('тест', encoding='utf-8') in loc def test_InternalRedirect(self): # InternalRedirect - self.getPage("/internalredirect/") + self.getPage('/internalredirect/') self.assertBody('hello') self.assertStatus(200) # Test passthrough self.getPage( - "/internalredirect/petshop?user_id=Sir-not-appearing-in-this-film") + '/internalredirect/petshop?user_id=Sir-not-appearing-in-this-film') self.assertBody('0 images for Sir-not-appearing-in-this-film') self.assertStatus(200) # Test args - self.getPage("/internalredirect/petshop?user_id=parrot") + self.getPage('/internalredirect/petshop?user_id=parrot') self.assertBody('0 images for slug') self.assertStatus(200) # Test POST - self.getPage("/internalredirect/petshop", method="POST", - body="user_id=terrier") + self.getPage('/internalredirect/petshop', method='POST', + body='user_id=terrier') self.assertBody('0 images for fish') self.assertStatus(200) # Test ir before body read - self.getPage("/internalredirect/early_ir", method="POST", - body="arg=aha!") - self.assertBody("Something went horribly wrong.") + self.getPage('/internalredirect/early_ir', method='POST', + body='arg=aha!') + self.assertBody('Something went horribly wrong.') self.assertStatus(200) - self.getPage("/internalredirect/secure") + self.getPage('/internalredirect/secure') self.assertBody('Please log in') self.assertStatus(200) # Relative path in InternalRedirect. # Also tests request.prev. - self.getPage("/internalredirect/relative?a=3&b=5") - self.assertBody("a=3&b=5") + self.getPage('/internalredirect/relative?a=3&b=5') + self.assertBody('a=3&b=5') self.assertStatus(200) # InternalRedirect on error - self.getPage("/internalredirect/choke") + self.getPage('/internalredirect/choke') self.assertStatus(200) - self.assertBody("Something went horribly wrong.") + self.assertBody('Something went horribly wrong.') def testFlatten(self): - for url in ["/flatten/as_string", "/flatten/as_list", - "/flatten/as_yield", "/flatten/as_dblyield", - "/flatten/as_refyield"]: + for url in ['/flatten/as_string', '/flatten/as_list', + '/flatten/as_yield', '/flatten/as_dblyield', + '/flatten/as_refyield']: self.getPage(url) self.assertBody('content') def testRanges(self): - self.getPage("/ranges/get_ranges?bytes=3-6") - self.assertBody("[(3, 7)]") + self.getPage('/ranges/get_ranges?bytes=3-6') + self.assertBody('[(3, 7)]') # Test multiple ranges and a suffix-byte-range-spec, for good measure. - self.getPage("/ranges/get_ranges?bytes=2-4,-1") - self.assertBody("[(2, 5), (7, 8)]") + self.getPage('/ranges/get_ranges?bytes=2-4,-1') + self.assertBody('[(2, 5), (7, 8)]') # Test a suffix-byte-range longer than the content # length. Note that in this test, the content length # is 8 bytes. - self.getPage("/ranges/get_ranges?bytes=-100") - self.assertBody("[(0, 8)]") + self.getPage('/ranges/get_ranges?bytes=-100') + self.assertBody('[(0, 8)]') # Get a partial file. - if cherrypy.server.protocol_version == "HTTP/1.1": - self.getPage("/ranges/slice_file", [('Range', 'bytes=2-5')]) + if cherrypy.server.protocol_version == 'HTTP/1.1': + self.getPage('/ranges/slice_file', [('Range', 'bytes=2-5')]) self.assertStatus(206) - self.assertHeader("Content-Type", "text/html;charset=utf-8") - self.assertHeader("Content-Range", "bytes 2-5/14") - self.assertBody("llo,") + self.assertHeader('Content-Type', 'text/html;charset=utf-8') + self.assertHeader('Content-Range', 'bytes 2-5/14') + self.assertBody('llo,') # What happens with overlapping ranges (and out of order, too)? - self.getPage("/ranges/slice_file", [('Range', 'bytes=4-6,2-5')]) + self.getPage('/ranges/slice_file', [('Range', 'bytes=4-6,2-5')]) self.assertStatus(206) - ct = self.assertHeader("Content-Type") - expected_type = "multipart/byteranges; boundary=" + ct = self.assertHeader('Content-Type') + expected_type = 'multipart/byteranges; boundary=' self.assert_(ct.startswith(expected_type)) boundary = ct[len(expected_type):] - expected_body = ("\r\n--%s\r\n" - "Content-type: text/html\r\n" - "Content-range: bytes 4-6/14\r\n" - "\r\n" - "o, \r\n" - "--%s\r\n" - "Content-type: text/html\r\n" - "Content-range: bytes 2-5/14\r\n" - "\r\n" - "llo,\r\n" - "--%s--\r\n" % (boundary, boundary, boundary)) + expected_body = ('\r\n--%s\r\n' + 'Content-type: text/html\r\n' + 'Content-range: bytes 4-6/14\r\n' + '\r\n' + 'o, \r\n' + '--%s\r\n' + 'Content-type: text/html\r\n' + 'Content-range: bytes 2-5/14\r\n' + '\r\n' + 'llo,\r\n' + '--%s--\r\n' % (boundary, boundary, boundary)) self.assertBody(expected_body) - self.assertHeader("Content-Length") + self.assertHeader('Content-Length') # Test "416 Requested Range Not Satisfiable" - self.getPage("/ranges/slice_file", [('Range', 'bytes=2300-2900')]) + self.getPage('/ranges/slice_file', [('Range', 'bytes=2300-2900')]) self.assertStatus(416) # "When this status code is returned for a byte-range request, # the response SHOULD include a Content-Range entity-header # field specifying the current length of the selected resource" - self.assertHeader("Content-Range", "bytes */14") - elif cherrypy.server.protocol_version == "HTTP/1.0": + self.assertHeader('Content-Range', 'bytes */14') + elif cherrypy.server.protocol_version == 'HTTP/1.0': # Test Range behavior with HTTP/1.0 request - self.getPage("/ranges/slice_file", [('Range', 'bytes=2-5')]) + self.getPage('/ranges/slice_file', [('Range', 'bytes=2-5')]) self.assertStatus(200) - self.assertBody("Hello, world\r\n") + self.assertBody('Hello, world\r\n') def testFavicon(self): # favicon.ico is served by staticfile. - icofilename = os.path.join(localDir, "../favicon.ico") - icofile = open(icofilename, "rb") + icofilename = os.path.join(localDir, '../favicon.ico') + icofile = open(icofilename, 'rb') data = icofile.read() icofile.close() - self.getPage("/favicon.ico") + self.getPage('/favicon.ico') self.assertBody(data) def skip_if_bad_cookies(self): @@ -575,23 +575,23 @@ class CoreRequestHandlingTest(helper.CPWebCase): if not _is_legal_key(','): return issue = 'http://bugs.python.org/issue26302' - tmpl = "Broken cookies module ({issue})" + tmpl = 'Broken cookies module ({issue})' self.skip(tmpl.format(**locals())) def testCookies(self): self.skip_if_bad_cookies() - self.getPage("/cookies/single?name=First", + self.getPage('/cookies/single?name=First', [('Cookie', 'First=Dinsdale;')]) self.assertHeader('Set-Cookie', 'First=Dinsdale') - self.getPage("/cookies/multiple?names=First&names=Last", + self.getPage('/cookies/multiple?names=First&names=Last', [('Cookie', 'First=Dinsdale; Last=Piranha;'), ]) self.assertHeader('Set-Cookie', 'First=Dinsdale') self.assertHeader('Set-Cookie', 'Last=Piranha') - self.getPage("/cookies/single?name=Something-With%2CComma", + self.getPage('/cookies/single?name=Something-With%2CComma', [('Cookie', 'Something-With,Comma=some-value')]) self.assertStatus(400) @@ -682,40 +682,40 @@ class CoreRequestHandlingTest(helper.CPWebCase): def test_expose_decorator(self): # Test @expose - self.getPage("/expose_dec/no_call") + self.getPage('/expose_dec/no_call') self.assertStatus(200) - self.assertBody("Mr E. R. Bradshaw") + self.assertBody('Mr E. R. Bradshaw') # Test @expose() - self.getPage("/expose_dec/call_empty") + self.getPage('/expose_dec/call_empty') self.assertStatus(200) - self.assertBody("Mrs. B.J. Smegma") + self.assertBody('Mrs. B.J. Smegma') # Test @expose("alias") - self.getPage("/expose_dec/call_alias") + self.getPage('/expose_dec/call_alias') self.assertStatus(200) - self.assertBody("Mr Nesbitt") + self.assertBody('Mr Nesbitt') # Does the original name work? - self.getPage("/expose_dec/nesbitt") + self.getPage('/expose_dec/nesbitt') self.assertStatus(200) - self.assertBody("Mr Nesbitt") + self.assertBody('Mr Nesbitt') # Test @expose(["alias1", "alias2"]) - self.getPage("/expose_dec/alias1") + self.getPage('/expose_dec/alias1') self.assertStatus(200) - self.assertBody("Mr Ken Andrews") - self.getPage("/expose_dec/alias2") + self.assertBody('Mr Ken Andrews') + self.getPage('/expose_dec/alias2') self.assertStatus(200) - self.assertBody("Mr Ken Andrews") + self.assertBody('Mr Ken Andrews') # Does the original name work? - self.getPage("/expose_dec/andrews") + self.getPage('/expose_dec/andrews') self.assertStatus(200) - self.assertBody("Mr Ken Andrews") + self.assertBody('Mr Ken Andrews') # Test @expose(alias="alias") - self.getPage("/expose_dec/alias3") + self.getPage('/expose_dec/alias3') self.assertStatus(200) - self.assertBody("Mr. and Mrs. Watson") + self.assertBody('Mr. and Mrs. Watson') class ErrorTests(helper.CPWebCase): @@ -732,11 +732,11 @@ class ErrorTests(helper.CPWebCase): @cherrypy.expose def index(self): - return "hello" + return 'hello' @cherrypy.config(**{'tools.break_header.on': True}) def start_response_error(self): - return "salud!" + return 'salud!' @cherrypy.expose def stat(self, path): @@ -748,12 +748,12 @@ class ErrorTests(helper.CPWebCase): cherrypy.tree.mount(root) def test_start_response_error(self): - self.getPage("/start_response_error") + self.getPage('/start_response_error') self.assertStatus(500) self.assertInBody( - "TypeError: response.header_list key 2 is not a byte string.") + 'TypeError: response.header_list key 2 is not a byte string.') def test_contextmanager(self): - self.getPage("/stat/missing") + self.getPage('/stat/missing') self.assertStatus(404) - self.assertInBody("No such file or directory") + self.assertInBody('No such file or directory') diff --git a/cherrypy/test/test_dynamicobjectmapping.py b/cherrypy/test/test_dynamicobjectmapping.py index 331c3f2e..54b0dcb7 100644 --- a/cherrypy/test/test_dynamicobjectmapping.py +++ b/cherrypy/test/test_dynamicobjectmapping.py @@ -4,7 +4,7 @@ import cherrypy from cherrypy._cpcompat import sorted from cherrypy.test import helper -script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"] +script_names = ['', '/foo', '/users/fred/blog', '/corp/blog'] def setup_server(): @@ -12,19 +12,19 @@ def setup_server(): @cherrypy.expose def index(self): - return "SubSubRoot index" + return 'SubSubRoot index' @cherrypy.expose def default(self, *args): - return "SubSubRoot default" + return 'SubSubRoot default' @cherrypy.expose def handler(self): - return "SubSubRoot handler" + return 'SubSubRoot handler' @cherrypy.expose def dispatch(self): - return "SubSubRoot dispatch" + return 'SubSubRoot dispatch' subsubnodes = { '1': SubSubRoot(), @@ -35,15 +35,15 @@ def setup_server(): @cherrypy.expose def index(self): - return "SubRoot index" + return 'SubRoot index' @cherrypy.expose def default(self, *args): - return "SubRoot %s" % (args,) + return 'SubRoot %s' % (args,) @cherrypy.expose def handler(self): - return "SubRoot handler" + return 'SubRoot handler' def _cp_dispatch(self, vpath): return subsubnodes.get(vpath[0], None) @@ -57,15 +57,15 @@ def setup_server(): @cherrypy.expose def index(self): - return "index" + return 'index' @cherrypy.expose def default(self, *args): - return "default %s" % (args,) + return 'default %s' % (args,) @cherrypy.expose def handler(self): - return "handler" + return 'handler' def _cp_dispatch(self, vpath): return subnodes.get(vpath[0]) @@ -103,7 +103,7 @@ def setup_server(): """ Allow the creation of a new Object """ - return "POST %d" % make_user(name) + return 'POST %d' % make_user(name) def GET(self): return six.text_type(sorted(user_lookup.keys())) @@ -138,7 +138,7 @@ def setup_server(): Update the fields of the user instance. """ self.user.name = name - return "POST %d" % self.user.id + return 'POST %d' % self.user.id def PUT(self, name): """ @@ -148,10 +148,10 @@ def setup_server(): if self.user: # Edit the current user self.user.name = name - return "PUT %d" % self.user.id + return 'PUT %d' % self.user.id else: # Make a new user with said attributes. - return "PUT %d" % make_user(name, self.id) + return 'PUT %d' % make_user(name, self.id) def DELETE(self): """ @@ -160,7 +160,7 @@ def setup_server(): id = self.user.id del user_lookup[self.user.id] del self.user - return "DELETE %d" % id + return 'DELETE %d' % id class ABHandler: @@ -168,7 +168,7 @@ def setup_server(): @cherrypy.expose def index(self, a, b): - return "custom" + return 'custom' def _cp_dispatch(self, vpath): """Make sure that if we don't pop anything from vpath, @@ -199,7 +199,7 @@ def setup_server(): @cherrypy.expose def index(self): - return "IndexOnly index" + return 'IndexOnly index' class DecoratedPopArgs: @@ -207,7 +207,7 @@ def setup_server(): @cherrypy.expose def index(self): - return "no params" + return 'no params' @cherrypy.expose def hi(self): @@ -223,7 +223,7 @@ def setup_server(): @cherrypy.expose def index(self, a): - return "index: " + str(a) + return 'index: ' + str(a) class ParameterizedHandler: @@ -236,8 +236,8 @@ def setup_server(): def index(self): if 'a' in cherrypy.request.params: raise Exception( - "Parameterized handler argument ended up in " - "request.params") + 'Parameterized handler argument ended up in ' + 'request.params') return self.a class ParameterizedPopArgs: @@ -256,7 +256,7 @@ def setup_server(): md = cherrypy.dispatch.MethodDispatcher('dynamic_dispatch') for url in script_names: conf = {'/': { - 'user': (url or "/").split("/")[-2], + 'user': (url or '/').split('/')[-2], }, '/users': { 'request.dispatch': md @@ -323,7 +323,7 @@ class DynamicObjectMappingTest(helper.CPWebCase): # The exposed dispatch will not be called as a dispatch # method. self.getPage('/2/2/foo/foo') - self.assertBody("SubSubRoot default") + self.assertBody('SubSubRoot default') # Dynamic dispatch will fail here for the subsubnodes # so the SubRoot gets called @@ -338,28 +338,28 @@ class DynamicObjectMappingTest(helper.CPWebCase): def testMethodDispatch(self): # GET acts like a container - self.getPage("/users") - self.assertBody("[1, 2]") + self.getPage('/users') + self.assertBody('[1, 2]') self.assertHeader('Allow', 'GET, HEAD, POST') # POST to the container URI allows creation - self.getPage("/users", method="POST", body="name=baz") - self.assertBody("POST 3") + self.getPage('/users', method='POST', body='name=baz') + self.assertBody('POST 3') self.assertHeader('Allow', 'GET, HEAD, POST') # POST to a specific instanct URI results in a 404 # as the resource does not exit. - self.getPage("/users/5", method="POST", body="name=baz") + self.getPage('/users/5', method='POST', body='name=baz') self.assertStatus(404) # PUT to a specific instanct URI results in creation - self.getPage("/users/5", method="PUT", body="name=boris") - self.assertBody("PUT 5") + self.getPage('/users/5', method='PUT', body='name=boris') + self.assertBody('PUT 5') self.assertHeader('Allow', 'DELETE, GET, HEAD, POST, PUT') # GET acts like a container - self.getPage("/users") - self.assertBody("[1, 2, 3, 5]") + self.getPage('/users') + self.assertBody('[1, 2, 3, 5]') self.assertHeader('Allow', 'GET, HEAD, POST') test_cases = ( @@ -369,56 +369,56 @@ class DynamicObjectMappingTest(helper.CPWebCase): (5, 'boris', 'borisupdated', 'DELETE, GET, HEAD, POST, PUT'), ) for id, name, updatedname, headers in test_cases: - self.getPage("/users/%d" % id) + self.getPage('/users/%d' % id) self.assertBody(name) self.assertHeader('Allow', headers) # Make sure POSTs update already existings resources - self.getPage("/users/%d" % - id, method='POST', body="name=%s" % updatedname) - self.assertBody("POST %d" % id) + self.getPage('/users/%d' % + id, method='POST', body='name=%s' % updatedname) + self.assertBody('POST %d' % id) self.assertHeader('Allow', headers) # Make sure PUTs Update already existing resources. - self.getPage("/users/%d" % - id, method='PUT', body="name=%s" % updatedname) - self.assertBody("PUT %d" % id) + self.getPage('/users/%d' % + id, method='PUT', body='name=%s' % updatedname) + self.assertBody('PUT %d' % id) self.assertHeader('Allow', headers) # Make sure DELETES Remove already existing resources. - self.getPage("/users/%d" % id, method='DELETE') - self.assertBody("DELETE %d" % id) + self.getPage('/users/%d' % id, method='DELETE') + self.assertBody('DELETE %d' % id) self.assertHeader('Allow', headers) # GET acts like a container - self.getPage("/users") - self.assertBody("[]") + self.getPage('/users') + self.assertBody('[]') self.assertHeader('Allow', 'GET, HEAD, POST') def testVpathDispatch(self): - self.getPage("/decorated/") - self.assertBody("no params") + self.getPage('/decorated/') + self.assertBody('no params') - self.getPage("/decorated/hi") + self.getPage('/decorated/hi') self.assertBody("hi was not interpreted as 'a' param") - self.getPage("/decorated/yo/") - self.assertBody("a:yo") + self.getPage('/decorated/yo/') + self.assertBody('a:yo') - self.getPage("/decorated/yo/there/") - self.assertBody("a:yo,b:there") + self.getPage('/decorated/yo/there/') + self.assertBody('a:yo,b:there') - self.getPage("/decorated/yo/there/delete") - self.assertBody("deleting yo and there") + self.getPage('/decorated/yo/there/delete') + self.assertBody('deleting yo and there') - self.getPage("/decorated/yo/there/handled_by_dispatch/") - self.assertBody("custom") + self.getPage('/decorated/yo/there/handled_by_dispatch/') + self.assertBody('custom') - self.getPage("/undecorated/blah/") - self.assertBody("index: blah") + self.getPage('/undecorated/blah/') + self.assertBody('index: blah') - self.getPage("/index_only/a/b/c/d/e/f/g/") - self.assertBody("IndexOnly index") + self.getPage('/index_only/a/b/c/d/e/f/g/') + self.assertBody('IndexOnly index') - self.getPage("/parameter_test/argument2/") - self.assertBody("argument2") + self.getPage('/parameter_test/argument2/') + self.assertBody('argument2') diff --git a/cherrypy/test/test_encoding.py b/cherrypy/test/test_encoding.py index 81a15727..de541f11 100644 --- a/cherrypy/test/test_encoding.py +++ b/cherrypy/test/test_encoding.py @@ -14,7 +14,7 @@ from cherrypy.test import helper europoundUnicode = ntou('£', encoding='utf-8') -sing = ntou("毛泽东: Sing, Little Birdie?", encoding='utf-8') +sing = ntou('毛泽东: Sing, Little Birdie?', encoding='utf-8') sing8 = sing.encode('utf-8') sing16 = sing.encode('utf-16') @@ -28,7 +28,7 @@ class EncodingTests(helper.CPWebCase): @cherrypy.expose def index(self, param): - assert param == europoundUnicode, "%r != %r" % ( + assert param == europoundUnicode, '%r != %r' % ( param, europoundUnicode) yield europoundUnicode @@ -55,7 +55,7 @@ class EncodingTests(helper.CPWebCase): @cherrypy.expose def reqparams(self, *args, **kwargs): return ntob(', ').join( - [": ".join((k, v)).encode('utf8') + [': '.join((k, v)).encode('utf8') for k, v in sorted(cherrypy.request.params.items())] ) @@ -73,7 +73,7 @@ class EncodingTests(helper.CPWebCase): @cherrypy.expose def index(self): - yield "Hello, world" + yield 'Hello, world' @cherrypy.expose # Turn encoding off so the gzip tool is the one doing the collapse. @@ -83,7 +83,7 @@ class EncodingTests(helper.CPWebCase): # (content-encoding was still gzip even though traceback # wasn't zipped). raise IndexError() - yield "Here be dragons" + yield 'Here be dragons' @cherrypy.expose @cherrypy.config(**{'response.stream': True}) @@ -92,7 +92,7 @@ class EncodingTests(helper.CPWebCase): # (content-encoding was still gzip even though traceback # wasn't zipped). raise IndexError() - yield "Here be dragons" + yield 'Here be dragons' class Decode: @@ -102,7 +102,7 @@ class EncodingTests(helper.CPWebCase): 'tools.decode.default_encoding': ['utf-16'], }) def extra_charset(self, *args, **kwargs): - return ', '.join([": ".join((k, v)) + return ', '.join([': '.join((k, v)) for k, v in cherrypy.request.params.items()]) @cherrypy.expose @@ -111,7 +111,7 @@ class EncodingTests(helper.CPWebCase): 'tools.decode.encoding': 'utf-16', }) def force_charset(self, *args, **kwargs): - return ', '.join([": ".join((k, v)) + return ', '.join([': '.join((k, v)) for k, v in cherrypy.request.params.items()]) root = Root() @@ -129,109 +129,109 @@ class EncodingTests(helper.CPWebCase): # Encoded utf8 query strings MUST be parsed correctly. # Here, q is the POUND SIGN U+00A3 encoded in utf8 and then %HEX - self.getPage("/reqparams?q=%C2%A3") + self.getPage('/reqparams?q=%C2%A3') # The return value will be encoded as utf8. - self.assertBody(ntob("q: \xc2\xa3")) + self.assertBody(ntob('q: \xc2\xa3')) # Query strings that are incorrectly encoded MUST raise 404. # Here, q is the POUND SIGN U+00A3 encoded in latin1 and then %HEX - self.getPage("/reqparams?q=%A3") + self.getPage('/reqparams?q=%A3') self.assertStatus(404) self.assertErrorPage( 404, - "The given query string could not be processed. Query " + 'The given query string could not be processed. Query ' "strings for this resource must be encoded with 'utf8'.") def test_urlencoded_decoding(self): # Test the decoding of an application/x-www-form-urlencoded entity. europoundUtf8 = europoundUnicode.encode('utf-8') - body = ntob("param=") + europoundUtf8 + body = ntob('param=') + europoundUtf8 self.getPage('/', method='POST', headers=[ - ("Content-Type", "application/x-www-form-urlencoded"), - ("Content-Length", str(len(body))), + ('Content-Type', 'application/x-www-form-urlencoded'), + ('Content-Length', str(len(body))), ], body=body), self.assertBody(europoundUtf8) # Encoded utf8 entities MUST be parsed and decoded correctly. # Here, q is the POUND SIGN U+00A3 encoded in utf8 - body = ntob("q=\xc2\xa3") + body = ntob('q=\xc2\xa3') self.getPage('/reqparams', method='POST', headers=[( - "Content-Type", "application/x-www-form-urlencoded"), - ("Content-Length", str(len(body))), + 'Content-Type', 'application/x-www-form-urlencoded'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("q: \xc2\xa3")) + self.assertBody(ntob('q: \xc2\xa3')) # ...and in utf16, which is not in the default attempt_charsets list: - body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00") + body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00') self.getPage('/reqparams', method='POST', headers=[ - ("Content-Type", - "application/x-www-form-urlencoded;charset=utf-16"), - ("Content-Length", str(len(body))), + ('Content-Type', + 'application/x-www-form-urlencoded;charset=utf-16'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("q: \xc2\xa3")) + self.assertBody(ntob('q: \xc2\xa3')) # Entities that are incorrectly encoded MUST raise 400. # Here, q is the POUND SIGN U+00A3 encoded in utf16, but # the Content-Type incorrectly labels it utf-8. - body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00") + body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00') self.getPage('/reqparams', method='POST', headers=[ - ("Content-Type", - "application/x-www-form-urlencoded;charset=utf-8"), - ("Content-Length", str(len(body))), + ('Content-Type', + 'application/x-www-form-urlencoded;charset=utf-8'), + ('Content-Length', str(len(body))), ], body=body), self.assertStatus(400) self.assertErrorPage( 400, - "The request entity could not be decoded. The following charsets " + 'The request entity could not be decoded. The following charsets ' "were attempted: ['utf-8']") def test_decode_tool(self): # An extra charset should be tried first, and succeed if it matches. # Here, we add utf-16 as a charset and pass a utf-16 body. - body = ntob("\xff\xfeq\x00=\xff\xfe\xa3\x00") + body = ntob('\xff\xfeq\x00=\xff\xfe\xa3\x00') self.getPage('/decode/extra_charset', method='POST', headers=[( - "Content-Type", "application/x-www-form-urlencoded"), - ("Content-Length", str(len(body))), + 'Content-Type', 'application/x-www-form-urlencoded'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("q: \xc2\xa3")) + self.assertBody(ntob('q: \xc2\xa3')) # An extra charset should be tried first, and continue to other default # charsets if it doesn't match. # Here, we add utf-16 as a charset but still pass a utf-8 body. - body = ntob("q=\xc2\xa3") + body = ntob('q=\xc2\xa3') self.getPage('/decode/extra_charset', method='POST', headers=[( - "Content-Type", "application/x-www-form-urlencoded"), - ("Content-Length", str(len(body))), + 'Content-Type', 'application/x-www-form-urlencoded'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("q: \xc2\xa3")) + self.assertBody(ntob('q: \xc2\xa3')) # An extra charset should error if force is True and it doesn't match. # Here, we force utf-16 as a charset but still pass a utf-8 body. - body = ntob("q=\xc2\xa3") + body = ntob('q=\xc2\xa3') self.getPage('/decode/force_charset', method='POST', headers=[( - "Content-Type", "application/x-www-form-urlencoded"), - ("Content-Length", str(len(body))), + 'Content-Type', 'application/x-www-form-urlencoded'), + ('Content-Length', str(len(body))), ], body=body), self.assertErrorPage( 400, - "The request entity could not be decoded. The following charsets " + 'The request entity could not be decoded. The following charsets ' "were attempted: ['utf-16']") def test_multipart_decoding(self): @@ -252,11 +252,11 @@ class EncodingTests(helper.CPWebCase): ])) self.getPage('/reqparams', method='POST', headers=[( - "Content-Type", "multipart/form-data;boundary=X"), - ("Content-Length", str(len(body))), + 'Content-Type', 'multipart/form-data;boundary=X'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("submit: Create, text: ab\xe2\x80\x9cc")) + self.assertBody(ntob('submit: Create, text: ab\xe2\x80\x9cc')) @mock.patch('cherrypy._cpreqbody.Part.maxrambytes', 1) def test_multipart_decoding_bigger_maxrambytes(self): @@ -282,11 +282,11 @@ class EncodingTests(helper.CPWebCase): ])) self.getPage('/reqparams', method='POST', headers=[( - "Content-Type", "multipart/form-data;boundary=X"), - ("Content-Length", str(len(body))), + 'Content-Type', 'multipart/form-data;boundary=X'), + ('Content-Length', str(len(body))), ], body=body), - self.assertBody(ntob("submit: Create, text: \xe2\x80\x9c")) + self.assertBody(ntob('submit: Create, text: \xe2\x80\x9c')) def test_multipart_decoding_no_successful_charset(self): # Test the decoding of a multipart entity when the charset (utf16) is @@ -304,14 +304,14 @@ class EncodingTests(helper.CPWebCase): ])) self.getPage('/reqparams', method='POST', headers=[( - "Content-Type", "multipart/form-data;boundary=X"), - ("Content-Length", str(len(body))), + 'Content-Type', 'multipart/form-data;boundary=X'), + ('Content-Length', str(len(body))), ], body=body), self.assertStatus(400) self.assertErrorPage( 400, - "The request entity could not be decoded. The following charsets " + 'The request entity could not be decoded. The following charsets ' "were attempted: ['us-ascii', 'utf-8']") def test_nontext(self): @@ -341,66 +341,66 @@ class EncodingTests(helper.CPWebCase): # Only allow iso-8859-1, which should fail and raise 406. self.getPage('/mao_zedong', [('Accept-Charset', 'iso-8859-1, *;q=0')]) - self.assertStatus("406 Not Acceptable") - self.assertInBody("Your client sent this Accept-Charset header: " - "iso-8859-1, *;q=0. We tried these charsets: " - "iso-8859-1.") + self.assertStatus('406 Not Acceptable') + self.assertInBody('Your client sent this Accept-Charset header: ' + 'iso-8859-1, *;q=0. We tried these charsets: ' + 'iso-8859-1.') # Ask for x-mac-ce, which should be unknown. See ticket #569. self.getPage('/mao_zedong', [('Accept-Charset', 'us-ascii, ISO-8859-1, x-mac-ce')]) - self.assertStatus("406 Not Acceptable") - self.assertInBody("Your client sent this Accept-Charset header: " - "us-ascii, ISO-8859-1, x-mac-ce. We tried these " - "charsets: ISO-8859-1, us-ascii, x-mac-ce.") + self.assertStatus('406 Not Acceptable') + self.assertInBody('Your client sent this Accept-Charset header: ' + 'us-ascii, ISO-8859-1, x-mac-ce. We tried these ' + 'charsets: ISO-8859-1, us-ascii, x-mac-ce.') # Test the 'encoding' arg to encode. self.getPage('/utf8') self.assertBody(sing8) self.getPage('/utf8', [('Accept-Charset', 'us-ascii, ISO-8859-1')]) - self.assertStatus("406 Not Acceptable") + self.assertStatus('406 Not Acceptable') def testGzip(self): zbuf = io.BytesIO() zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9) - zfile.write(ntob("Hello, world")) + zfile.write(ntob('Hello, world')) zfile.close() - self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip")]) + self.getPage('/gzip/', headers=[('Accept-Encoding', 'gzip')]) self.assertInBody(zbuf.getvalue()[:3]) - self.assertHeader("Vary", "Accept-Encoding") - self.assertHeader("Content-Encoding", "gzip") + self.assertHeader('Vary', 'Accept-Encoding') + self.assertHeader('Content-Encoding', 'gzip') # Test when gzip is denied. - self.getPage('/gzip/', headers=[("Accept-Encoding", "identity")]) - self.assertHeader("Vary", "Accept-Encoding") - self.assertNoHeader("Content-Encoding") - self.assertBody("Hello, world") + self.getPage('/gzip/', headers=[('Accept-Encoding', 'identity')]) + self.assertHeader('Vary', 'Accept-Encoding') + self.assertNoHeader('Content-Encoding') + self.assertBody('Hello, world') - self.getPage('/gzip/', headers=[("Accept-Encoding", "gzip;q=0")]) - self.assertHeader("Vary", "Accept-Encoding") - self.assertNoHeader("Content-Encoding") - self.assertBody("Hello, world") + self.getPage('/gzip/', headers=[('Accept-Encoding', 'gzip;q=0')]) + self.assertHeader('Vary', 'Accept-Encoding') + self.assertNoHeader('Content-Encoding') + self.assertBody('Hello, world') - self.getPage('/gzip/', headers=[("Accept-Encoding", "*;q=0")]) + self.getPage('/gzip/', headers=[('Accept-Encoding', '*;q=0')]) self.assertStatus(406) - self.assertNoHeader("Content-Encoding") - self.assertErrorPage(406, "identity, gzip") + self.assertNoHeader('Content-Encoding') + self.assertErrorPage(406, 'identity, gzip') # Test for ticket #147 - self.getPage('/gzip/noshow', headers=[("Accept-Encoding", "gzip")]) + self.getPage('/gzip/noshow', headers=[('Accept-Encoding', 'gzip')]) self.assertNoHeader('Content-Encoding') self.assertStatus(500) - self.assertErrorPage(500, pattern="IndexError\n") + self.assertErrorPage(500, pattern='IndexError\n') # In this case, there's nothing we can do to deliver a # readable page, since 1) the gzip header is already set, # and 2) we may have already written some of the body. # The fix is to never stream yields when using gzip. - if (cherrypy.server.protocol_version == "HTTP/1.0" or - getattr(cherrypy.server, "using_apache", False)): + if (cherrypy.server.protocol_version == 'HTTP/1.0' or + getattr(cherrypy.server, 'using_apache', False)): self.getPage('/gzip/noshow_stream', - headers=[("Accept-Encoding", "gzip")]) + headers=[('Accept-Encoding', 'gzip')]) self.assertHeader('Content-Encoding', 'gzip') self.assertInBody('\x1f\x8b\x08\x00') else: @@ -408,7 +408,7 @@ class EncodingTests(helper.CPWebCase): # will error due to an incomplete chunk-encoded stream. self.assertRaises((ValueError, IncompleteRead), self.getPage, '/gzip/noshow_stream', - headers=[("Accept-Encoding", "gzip")]) + headers=[('Accept-Encoding', 'gzip')]) def test_UnicodeHeaders(self): self.getPage('/cookies_and_headers') diff --git a/cherrypy/test/test_etags.py b/cherrypy/test/test_etags.py index 0ac6ef84..293eb866 100644 --- a/cherrypy/test/test_etags.py +++ b/cherrypy/test/test_etags.py @@ -11,7 +11,7 @@ class ETagTest(helper.CPWebCase): @cherrypy.expose def resource(self): - return "Oh wah ta goo Siam." + return 'Oh wah ta goo Siam.' @cherrypy.expose def fail(self, code): @@ -33,52 +33,52 @@ class ETagTest(helper.CPWebCase): cherrypy.tree.mount(Root(), config=conf) def test_etags(self): - self.getPage("/resource") + self.getPage('/resource') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html;charset=utf-8') self.assertBody('Oh wah ta goo Siam.') etag = self.assertHeader('ETag') # Test If-Match (both valid and invalid) - self.getPage("/resource", headers=[('If-Match', etag)]) - self.assertStatus("200 OK") - self.getPage("/resource", headers=[('If-Match', "*")]) - self.assertStatus("200 OK") - self.getPage("/resource", headers=[('If-Match', "*")], method="POST") - self.assertStatus("200 OK") - self.getPage("/resource", headers=[('If-Match', "a bogus tag")]) - self.assertStatus("412 Precondition Failed") + self.getPage('/resource', headers=[('If-Match', etag)]) + self.assertStatus('200 OK') + self.getPage('/resource', headers=[('If-Match', '*')]) + self.assertStatus('200 OK') + self.getPage('/resource', headers=[('If-Match', '*')], method='POST') + self.assertStatus('200 OK') + self.getPage('/resource', headers=[('If-Match', 'a bogus tag')]) + self.assertStatus('412 Precondition Failed') # Test If-None-Match (both valid and invalid) - self.getPage("/resource", headers=[('If-None-Match', etag)]) + self.getPage('/resource', headers=[('If-None-Match', etag)]) self.assertStatus(304) - self.getPage("/resource", method='POST', + self.getPage('/resource', method='POST', headers=[('If-None-Match', etag)]) - self.assertStatus("412 Precondition Failed") - self.getPage("/resource", headers=[('If-None-Match', "*")]) + self.assertStatus('412 Precondition Failed') + self.getPage('/resource', headers=[('If-None-Match', '*')]) self.assertStatus(304) - self.getPage("/resource", headers=[('If-None-Match', "a bogus tag")]) - self.assertStatus("200 OK") + self.getPage('/resource', headers=[('If-None-Match', 'a bogus tag')]) + self.assertStatus('200 OK') def test_errors(self): - self.getPage("/resource") + self.getPage('/resource') self.assertStatus(200) etag = self.assertHeader('ETag') # Test raising errors in page handler - self.getPage("/fail/412", headers=[('If-Match', etag)]) + self.getPage('/fail/412', headers=[('If-Match', etag)]) self.assertStatus(412) - self.getPage("/fail/304", headers=[('If-Match', etag)]) + self.getPage('/fail/304', headers=[('If-Match', etag)]) self.assertStatus(304) - self.getPage("/fail/412", headers=[('If-None-Match', "*")]) + self.getPage('/fail/412', headers=[('If-None-Match', '*')]) self.assertStatus(412) - self.getPage("/fail/304", headers=[('If-None-Match', "*")]) + self.getPage('/fail/304', headers=[('If-None-Match', '*')]) self.assertStatus(304) def test_unicode_body(self): - self.getPage("/unicoded") + self.getPage('/unicoded') self.assertStatus(200) etag1 = self.assertHeader('ETag') - self.getPage("/unicoded", headers=[('If-Match', etag1)]) + self.getPage('/unicoded', headers=[('If-Match', etag1)]) self.assertStatus(200) self.assertHeader('ETag', etag1) diff --git a/cherrypy/test/test_http.py b/cherrypy/test/test_http.py index 6a1c4bb8..f79e04fb 100644 --- a/cherrypy/test/test_http.py +++ b/cherrypy/test/test_http.py @@ -40,7 +40,7 @@ def encode_multipart_formdata(files): class HTTPTests(helper.CPWebCase): def make_connection(self): - if self.scheme == "https": + if self.scheme == 'https': return HTTPSConnection('%s:%s' % (self.interface(), self.PORT)) else: return HTTPConnection('%s:%s' % (self.interface(), self.PORT)) @@ -51,12 +51,12 @@ class HTTPTests(helper.CPWebCase): @cherrypy.expose def index(self, *args, **kwargs): - return "Hello world!" + return 'Hello world!' @cherrypy.expose @cherrypy.config(**{'request.process_request_body': False}) def no_body(self, *args, **kwargs): - return "Hello world!" + return 'Hello world!' @cherrypy.expose def post_multipart(self, file): @@ -74,14 +74,14 @@ class HTTPTests(helper.CPWebCase): if count: if six.PY3: curchar = chr(curchar) - summary.append("%s * %d" % (curchar, count)) + summary.append('%s * %d' % (curchar, count)) count = 1 curchar = c if count: if six.PY3: curchar = chr(curchar) - summary.append("%s * %d" % (curchar, count)) - return ", ".join(summary) + summary.append('%s * %d' % (curchar, count)) + return ', '.join(summary) @cherrypy.expose def post_filename(self, myfile): @@ -100,7 +100,7 @@ class HTTPTests(helper.CPWebCase): # the request is of method POST, this should be OK because we set # request.process_request_body to False for our handler. c = self.make_connection() - c.request("POST", "/no_body") + c.request('POST', '/no_body') response = c.getresponse() self.body = response.fp.read() self.status = str(response.status) @@ -110,7 +110,7 @@ class HTTPTests(helper.CPWebCase): # Now send a message that has no Content-Length, but does send a body. # Verify that CP times out the socket and responds # with 411 Length Required. - if self.scheme == "https": + if self.scheme == 'https': c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT)) else: c = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) @@ -119,7 +119,7 @@ class HTTPTests(helper.CPWebCase): with patch.object(c, '_get_content_length', lambda body, method: None, create=True): # `_set_content_length` is needed for Python 2.7-3.5 with patch.object(c, '_set_content_length', create=True): - c.request("POST", "/") + c.request('POST', '/') response = c.getresponse() self.body = response.fp.read() @@ -127,9 +127,9 @@ class HTTPTests(helper.CPWebCase): self.assertStatus(411) def test_post_multipart(self): - alphabet = "abcdefghijklmnopqrstuvwxyz" + alphabet = 'abcdefghijklmnopqrstuvwxyz' # generate file contents for a large post - contents = "".join([c * 65536 for c in alphabet]) + contents = ''.join([c * 65536 for c in alphabet]) # encode as multipart form data files = [('file', 'file.txt', contents)] @@ -148,7 +148,7 @@ class HTTPTests(helper.CPWebCase): self.body = response.fp.read() self.status = str(response.status) self.assertStatus(200) - self.assertBody(", ".join(["%s * 65536" % c for c in alphabet])) + self.assertBody(', '.join(['%s * 65536' % c for c in alphabet])) def test_post_filename_with_special_characters(self): '''Testing that we can handle filenames with special characters. This @@ -178,8 +178,8 @@ class HTTPTests(helper.CPWebCase): self.assertBody(fname) def test_malformed_request_line(self): - if getattr(cherrypy.server, "using_apache", False): - return self.skip("skipped due to known Apache differences...") + if getattr(cherrypy.server, 'using_apache', False): + return self.skip('skipped due to known Apache differences...') # Test missing version in Request-Line c = self.make_connection() @@ -193,7 +193,7 @@ class HTTPTests(helper.CPWebCase): response = c.response_class(c.sock, method='GET') response.begin() self.assertEqual(response.status, 400) - self.assertEqual(response.fp.read(22), ntob("Malformed Request-Line")) + self.assertEqual(response.fp.read(22), ntob('Malformed Request-Line')) c.close() def test_request_line_split_issue_1220(self): @@ -202,9 +202,9 @@ class HTTPTests(helper.CPWebCase): '&_path=intervenant-entreprise-evenement&intervenant-entreprise-evenement_action-id=19404' '&intervenant-entreprise-evenement_id=19404&intervenant-entreprise_id=28092' ) - self.assertEqual(len("GET %s HTTP/1.1\r\n" % Request_URI), 256) + self.assertEqual(len('GET %s HTTP/1.1\r\n' % Request_URI), 256) self.getPage(Request_URI) - self.assertBody("Hello world!") + self.assertBody('Hello world!') def test_malformed_header(self): c = self.make_connection() @@ -218,24 +218,24 @@ class HTTPTests(helper.CPWebCase): self.status = str(response.status) self.assertStatus(400) self.body = response.fp.read(20) - self.assertBody("Illegal header line.") + self.assertBody('Illegal header line.') def test_http_over_https(self): if self.scheme != 'https': - return self.skip("skipped (not running HTTPS)... ") + return self.skip('skipped (not running HTTPS)... ') # Try connecting without SSL. conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) - conn.putrequest("GET", "/", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') try: response.begin() self.assertEqual(response.status, 400) self.body = response.read() - self.assertBody("The client sent a plain HTTP request, but this " - "server only speaks HTTPS on this port.") + self.assertBody('The client sent a plain HTTP request, but this ' + 'server only speaks HTTPS on this port.') except socket.error: e = sys.exc_info()[1] # "Connection reset by peer" is also acceptable. @@ -247,12 +247,12 @@ class HTTPTests(helper.CPWebCase): c = HTTPConnection('%s:%s' % (self.interface(), self.PORT)) c._output(ntob('gjkgjklsgjklsgjkljklsg')) c._send_output() - response = c.response_class(c.sock, method="GET") + response = c.response_class(c.sock, method='GET') try: response.begin() self.assertEqual(response.status, 400) self.assertEqual(response.fp.read(22), - ntob("Malformed Request-Line")) + ntob('Malformed Request-Line')) c.close() except socket.error: e = sys.exc_info()[1] diff --git a/cherrypy/test/test_httpauth.py b/cherrypy/test/test_httpauth.py index db2b9445..3a5cff27 100644 --- a/cherrypy/test/test_httpauth.py +++ b/cherrypy/test/test_httpauth.py @@ -15,7 +15,7 @@ class HTTPAuthTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "This is public." + return 'This is public.' class DigestProtected: @@ -75,13 +75,13 @@ class HTTPAuthTest(helper.CPWebCase): cherrypy.tree.mount(root, config=conf) def testPublic(self): - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html;charset=utf-8') self.assertBody('This is public.') def testBasic(self): - self.getPage("/basic/") + self.getPage('/basic/') self.assertStatus(401) self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"') @@ -93,7 +93,7 @@ class HTTPAuthTest(helper.CPWebCase): self.assertBody("Hello test, you've been authorized.") def testBasic2(self): - self.getPage("/basic2/") + self.getPage('/basic2/') self.assertStatus(401) self.assertHeader('WWW-Authenticate', 'Basic realm="localhost"') @@ -105,19 +105,19 @@ class HTTPAuthTest(helper.CPWebCase): self.assertBody("Hello test, you've been authorized.") def testDigest(self): - self.getPage("/digest/") + self.getPage('/digest/') self.assertStatus(401) value = None for k, v in self.headers: - if k.lower() == "www-authenticate": - if v.startswith("Digest"): + if k.lower() == 'www-authenticate': + if v.startswith('Digest'): value = v break if value is None: self._handlewebError( - "Digest authentification scheme was not found") + 'Digest authentification scheme was not found') value = value[7:] items = value.split(', ') @@ -126,7 +126,7 @@ class HTTPAuthTest(helper.CPWebCase): key, value = item.split('=') tokens[key.lower()] = value - missing_msg = "%s is missing" + missing_msg = '%s is missing' bad_value_msg = "'%s' was expecting '%s' but found '%s'" nonce = None if 'realm' not in tokens: diff --git a/cherrypy/test/test_httplib.py b/cherrypy/test/test_httplib.py index 76ca7641..bba4a35e 100644 --- a/cherrypy/test/test_httplib.py +++ b/cherrypy/test/test_httplib.py @@ -8,22 +8,22 @@ class UtilityTests(unittest.TestCase): def test_urljoin(self): # Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO - self.assertEqual(httputil.urljoin("/sn/", "/pi/"), "/sn/pi/") - self.assertEqual(httputil.urljoin("/sn/", "/pi"), "/sn/pi") - self.assertEqual(httputil.urljoin("/sn/", "/"), "/sn/") - self.assertEqual(httputil.urljoin("/sn/", ""), "/sn/") - self.assertEqual(httputil.urljoin("/sn", "/pi/"), "/sn/pi/") - self.assertEqual(httputil.urljoin("/sn", "/pi"), "/sn/pi") - self.assertEqual(httputil.urljoin("/sn", "/"), "/sn/") - self.assertEqual(httputil.urljoin("/sn", ""), "/sn") - self.assertEqual(httputil.urljoin("/", "/pi/"), "/pi/") - self.assertEqual(httputil.urljoin("/", "/pi"), "/pi") - self.assertEqual(httputil.urljoin("/", "/"), "/") - self.assertEqual(httputil.urljoin("/", ""), "/") - self.assertEqual(httputil.urljoin("", "/pi/"), "/pi/") - self.assertEqual(httputil.urljoin("", "/pi"), "/pi") - self.assertEqual(httputil.urljoin("", "/"), "/") - self.assertEqual(httputil.urljoin("", ""), "/") + self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/') + self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi') + self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/') + self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/') + self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/') + self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi') + self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/') + self.assertEqual(httputil.urljoin('/sn', ''), '/sn') + self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/') + self.assertEqual(httputil.urljoin('/', '/pi'), '/pi') + self.assertEqual(httputil.urljoin('/', '/'), '/') + self.assertEqual(httputil.urljoin('/', ''), '/') + self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/') + self.assertEqual(httputil.urljoin('', '/pi'), '/pi') + self.assertEqual(httputil.urljoin('', '/'), '/') + self.assertEqual(httputil.urljoin('', ''), '/') if __name__ == '__main__': unittest.main() diff --git a/cherrypy/test/test_iterator.py b/cherrypy/test/test_iterator.py index 90872f3a..7cc54d48 100644 --- a/cherrypy/test/test_iterator.py +++ b/cherrypy/test/test_iterator.py @@ -100,13 +100,13 @@ class IteratorTest(helper.CPWebCase): try: self._test_iterator() except Exception: - "Test fails intermittently. See #1419" + 'Test fails intermittently. See #1419' def _test_iterator(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Check the counts of all the classes, they should be zero. closables = ['OurClosableIterator', 'OurGenerator'] @@ -117,7 +117,7 @@ class IteratorTest(helper.CPWebCase): random.shuffle(all_classes) for clsname in all_classes: - self.getPage("/count/" + clsname) + self.getPage('/count/' + clsname) self.assertStatus(200) self.assertBody('0') @@ -126,7 +126,7 @@ class IteratorTest(helper.CPWebCase): # check the header. for clsname in all_classes: itr_conn = self.get_conn() - itr_conn.putrequest("GET", "/getall/" + clsname) + itr_conn.putrequest('GET', '/getall/' + clsname) itr_conn.endheaders() response = itr_conn.getresponse() self.assertEqual(response.status, 200) @@ -141,7 +141,7 @@ class IteratorTest(helper.CPWebCase): # As the response should be fully consumed by CherryPy # before sending back, the count should still be at zero # by the time the response has been sent. - self.getPage("/count/" + clsname) + self.getPage('/count/' + clsname) self.assertStatus(200) self.assertBody('0') @@ -150,20 +150,20 @@ class IteratorTest(helper.CPWebCase): stream_counts = {} for clsname in all_classes: itr_conn = self.get_conn() - itr_conn.putrequest("GET", "/stream/" + clsname) + itr_conn.putrequest('GET', '/stream/' + clsname) itr_conn.endheaders() response = itr_conn.getresponse() self.assertEqual(response.status, 200) response.fp.read(65536) # Let's check the count - this should always be one. - self.getPage("/count/" + clsname) + self.getPage('/count/' + clsname) self.assertBody('1') # Now if we close the connection, the count should go back # to zero. itr_conn.close() - self.getPage("/count/" + clsname) + self.getPage('/count/' + clsname) # If this is a response which should be easily closed, then # we will test to see if the value has gone back down to @@ -176,7 +176,7 @@ class IteratorTest(helper.CPWebCase): if self.body != '0': import time time.sleep(0.1) - self.getPage("/count/" + clsname) + self.getPage('/count/' + clsname) stream_counts[clsname] = int(self.body) diff --git a/cherrypy/test/test_json.py b/cherrypy/test/test_json.py index 7dffb429..921971e6 100644 --- a/cherrypy/test/test_json.py +++ b/cherrypy/test/test_json.py @@ -51,51 +51,51 @@ class JsonTest(helper.CPWebCase): def test_json_output(self): if json is None: - self.skip("json not found ") + self.skip('json not found ') return - self.getPage("/plain") - self.assertBody("hello") + self.getPage('/plain') + self.assertBody('hello') - self.getPage("/json_string") + self.getPage('/json_string') self.assertBody('"hello"') - self.getPage("/json_list") + self.getPage('/json_list') self.assertBody('["a", "b", 42]') - self.getPage("/json_dict") + self.getPage('/json_dict') self.assertBody('{"answer": 42}') def test_json_input(self): if json is None: - self.skip("json not found ") + self.skip('json not found ') return body = '[13, "c"]' headers = [('Content-Type', 'application/json'), ('Content-Length', str(len(body)))] - self.getPage("/json_post", method="POST", headers=headers, body=body) + self.getPage('/json_post', method='POST', headers=headers, body=body) self.assertBody('ok') body = '[13, "c"]' headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(body)))] - self.getPage("/json_post", method="POST", headers=headers, body=body) + self.getPage('/json_post', method='POST', headers=headers, body=body) self.assertStatus(415, 'Expected an application/json content type') body = '[13, -]' headers = [('Content-Type', 'application/json'), ('Content-Length', str(len(body)))] - self.getPage("/json_post", method="POST", headers=headers, body=body) + self.getPage('/json_post', method='POST', headers=headers, body=body) self.assertStatus(400, 'Invalid JSON document') def test_cached(self): if json is None: - self.skip("json not found ") + self.skip('json not found ') return - self.getPage("/json_cached") + self.getPage('/json_cached') self.assertStatus(200, '"hello"') - self.getPage("/json_cached") # 2'nd time to hit cache + self.getPage('/json_cached') # 2'nd time to hit cache self.assertStatus(200, '"hello"') diff --git a/cherrypy/test/test_logging.py b/cherrypy/test/test_logging.py index 254ee2c7..51628dda 100644 --- a/cherrypy/test/test_logging.py +++ b/cherrypy/test/test_logging.py @@ -9,8 +9,8 @@ from cherrypy._cpcompat import ntob, ntou from cherrypy.test import helper, logtest localDir = os.path.dirname(__file__) -access_log = os.path.join(localDir, "access.log") -error_log = os.path.join(localDir, "error.log") +access_log = os.path.join(localDir, 'access.log') +error_log = os.path.join(localDir, 'error.log') # Some unicode strings. tartaros = ntou('\u03a4\u1f71\u03c1\u03c4\u03b1\u03c1\u03bf\u03c2', 'escape') @@ -22,7 +22,7 @@ def setup_server(): @cherrypy.expose def index(self): - return "hello" + return 'hello' @cherrypy.expose def uni_code(self): @@ -44,11 +44,11 @@ def setup_server(): @cherrypy.expose def as_string(self): - return "content" + return 'content' @cherrypy.expose def as_yield(self): - yield "content" + yield 'content' @cherrypy.expose @cherrypy.config(**{'tools.log_tracebacks.on': True}) @@ -71,7 +71,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): def testNormalReturn(self): self.markLog() - self.getPage("/as_string", + self.getPage('/as_string', headers=[('Referer', 'http://www.cherrypy.org/'), ('User-Agent', 'Mozilla/5.0')]) self.assertBody('content') @@ -92,7 +92,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): def testNormalYield(self): self.markLog() - self.getPage("/as_yield") + self.getPage('/as_yield') self.assertBody('content') self.assertStatus(200) @@ -117,7 +117,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" %(o)s' self.markLog() - self.getPage("/as_string", headers=[('Referer', 'REFERER'), + self.getPage('/as_string', headers=[('Referer', 'REFERER'), ('User-Agent', 'USERAGENT'), ('Host', 'HOST')]) self.assertLog(-1, '%s - - [' % self.interface()) @@ -129,7 +129,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): def testEscapedOutput(self): # Test unicode in access log pieces. self.markLog() - self.getPage("/uni_code") + self.getPage('/uni_code') self.assertStatus(200) if six.PY3: # The repr of a bytestring in six.PY3 includes a b'' prefix @@ -142,7 +142,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): # Test backslashes in output. self.markLog() - self.getPage("/slashes") + self.getPage('/slashes') self.assertStatus(200) if six.PY3: self.assertLog(-1, ntob('"GET /slashed\\path HTTP/1.1"')) @@ -151,7 +151,7 @@ class AccessLogTests(helper.CPWebCase, logtest.LogCase): # Test whitespace in output. self.markLog() - self.getPage("/whitespace") + self.getPage('/whitespace') self.assertStatus(200) # Again, note the 'r' prefix. self.assertLog(-1, r'"Browzuh (1.0\r\n\t\t.3)"') @@ -168,8 +168,8 @@ class ErrorLogTests(helper.CPWebCase, logtest.LogCase): ignore = helper.webtest.ignored_exceptions ignore.append(ValueError) try: - self.getPage("/error") - self.assertInBody("raise ValueError()") + self.getPage('/error') + self.assertInBody('raise ValueError()') self.assertLog(0, 'HTTP') self.assertLog(1, 'Traceback (most recent call last):') self.assertLog(-2, 'raise ValueError()') diff --git a/cherrypy/test/test_mime.py b/cherrypy/test/test_mime.py index f52a241e..912bde5f 100644 --- a/cherrypy/test/test_mime.py +++ b/cherrypy/test/test_mime.py @@ -19,7 +19,7 @@ def setup_server(): @cherrypy.expose def flashupload(self, Filedata, Upload, Filename): - return ("Upload: %s, Filename: %s, Filedata: %r" % + return ('Upload: %s, Filename: %s, Filedata: %r' % (Upload, Filename, Filedata.file.read())) cherrypy.config.update({'server.max_request_body_size': 0}) @@ -33,7 +33,7 @@ class MultipartTest(helper.CPWebCase): setup_server = staticmethod(setup_server) def test_multipart(self): - text_part = ntou("This is the text version") + text_part = ntou('This is the text version') html_part = ntou( """<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> @@ -47,21 +47,21 @@ This is the <strong>HTML</strong> version </html> """) body = '\r\n'.join([ - "--123456789", + '--123456789', "Content-Type: text/plain; charset='ISO-8859-1'", - "Content-Transfer-Encoding: 7bit", - "", + 'Content-Transfer-Encoding: 7bit', + '', text_part, - "--123456789", + '--123456789', "Content-Type: text/html; charset='ISO-8859-1'", - "", + '', html_part, - "--123456789--"]) + '--123456789--']) headers = [ ('Content-Type', 'multipart/mixed; boundary=123456789'), ('Content-Length', str(len(body))), ] - self.getPage('/multipart', headers, "POST", body) + self.getPage('/multipart', headers, 'POST', body) self.assertBody(repr([text_part, html_part])) def test_multipart_form_data(self): @@ -85,8 +85,8 @@ This is the <strong>HTML</strong> version ]) self.getPage('/multipart_form_data', method='POST', headers=[( - "Content-Type", "multipart/form-data;boundary=X"), - ("Content-Length", str(len(body))), + 'Content-Type', 'multipart/form-data;boundary=X'), + ('Content-Length', str(len(body))), ], body=body), self.assertBody( @@ -129,6 +129,6 @@ class SafeMultipartHandlingTest(helper.CPWebCase): # Flash apps omit the trailing \r\n on the last line: '------------KM7Ij5cH2KM7Ef1gL6ae0ae0cH2gL6--' )) - self.getPage('/flashupload', headers, "POST", body) - self.assertBody("Upload: Submit Query, Filename: .project, " - "Filedata: %r" % filedata) + self.getPage('/flashupload', headers, 'POST', body) + self.assertBody('Upload: Submit Query, Filename: .project, ' + 'Filedata: %r' % filedata) diff --git a/cherrypy/test/test_misc_tools.py b/cherrypy/test/test_misc_tools.py index b2565798..ad776000 100644 --- a/cherrypy/test/test_misc_tools.py +++ b/cherrypy/test/test_misc_tools.py @@ -6,7 +6,7 @@ from cherrypy.test import helper localDir = os.path.dirname(__file__) -logfile = os.path.join(localDir, "test_misc_tools.log") +logfile = os.path.join(localDir, 'test_misc_tools.log') def setup_server(): @@ -14,21 +14,21 @@ def setup_server(): @cherrypy.expose def index(self): - yield "Hello, world" - h = [("Content-Language", "en-GB"), ('Content-Type', 'text/plain')] + yield 'Hello, world' + h = [('Content-Language', 'en-GB'), ('Content-Type', 'text/plain')] tools.response_headers(headers=h)(index) @cherrypy.expose @cherrypy.config(**{ 'tools.response_headers.on': True, 'tools.response_headers.headers': [ - ("Content-Language", "fr"), + ('Content-Language', 'fr'), ('Content-Type', 'text/plain'), ], 'tools.log_hooks.on': True, }) def other(self): - return "salut" + return 'salut' @cherrypy.config(**{'tools.accept.on': True}) class Accept: @@ -52,15 +52,15 @@ def setup_server(): # We could also write this: mtype = cherrypy.lib.accept.accept(...) mtype = tools.accept.callable(['text/html', 'text/plain']) if mtype == 'text/html': - return "<h2>Page Title</h2>" + return '<h2>Page Title</h2>' else: - return "PAGE TITLE" + return 'PAGE TITLE' class Referer: @cherrypy.expose def accept(self): - return "Accepted!" + return 'Accepted!' reject = accept class AutoVary: @@ -82,7 +82,7 @@ def setup_server(): has = 'Range' in cherrypy.request.headers # Call a lib function mtype = tools.accept.callable(['text/html', 'text/plain']) - return "Hello, world!" + return 'Hello, world!' conf = {'/referer': {'tools.referer.on': True, 'tools.referer.pattern': r'http://[^/]*example\.com', @@ -106,12 +106,12 @@ class ResponseHeadersTest(helper.CPWebCase): def testResponseHeadersDecorator(self): self.getPage('/') - self.assertHeader("Content-Language", "en-GB") + self.assertHeader('Content-Language', 'en-GB') self.assertHeader('Content-Type', 'text/plain;charset=utf-8') def testResponseHeaders(self): self.getPage('/other') - self.assertHeader("Content-Language", "fr") + self.assertHeader('Content-Language', 'fr') self.assertHeader('Content-Type', 'text/plain;charset=utf-8') @@ -165,9 +165,9 @@ class AcceptTest(helper.CPWebCase): # Specify unacceptable media types self.getPage('/accept/feed', headers=[('Accept', 'text/html')]) self.assertErrorPage(406, - "Your client sent this Accept header: text/html. " - "But this resource only emits these media types: " - "application/atom+xml.") + 'Your client sent this Accept header: text/html. ' + 'But this resource only emits these media types: ' + 'application/atom+xml.') # Test resource where tool is 'on' but media is None (not set). self.getPage('/accept/') @@ -200,9 +200,9 @@ class AcceptTest(helper.CPWebCase): self.getPage('/accept/select', [('Accept', 'application/xml')]) self.assertErrorPage( 406, - "Your client sent this Accept header: application/xml. " - "But this resource only emits these media types: " - "text/html, text/plain.") + 'Your client sent this Accept header: application/xml. ' + 'But this resource only emits these media types: ' + 'text/html, text/plain.') class AutoVaryTest(helper.CPWebCase): @@ -211,7 +211,7 @@ class AutoVaryTest(helper.CPWebCase): def testAutoVary(self): self.getPage('/autovary/') self.assertHeader( - "Vary", + 'Vary', 'Accept, Accept-Charset, Accept-Encoding, ' 'Host, If-Modified-Since, Range' ) diff --git a/cherrypy/test/test_objectmapping.py b/cherrypy/test/test_objectmapping.py index c2b90bdc..d1362932 100644 --- a/cherrypy/test/test_objectmapping.py +++ b/cherrypy/test/test_objectmapping.py @@ -4,7 +4,7 @@ from cherrypy._cpcompat import ntou from cherrypy._cptree import Application from cherrypy.test import helper -script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"] +script_names = ['', '/foo', '/users/fred/blog', '/corp/blog'] class ObjectMappingTest(helper.CPWebCase): @@ -14,20 +14,20 @@ class ObjectMappingTest(helper.CPWebCase): class Root: @cherrypy.expose - def index(self, name="world"): + def index(self, name='world'): return name @cherrypy.expose def foobar(self): - return "bar" + return 'bar' @cherrypy.expose def default(self, *params, **kwargs): - return "default:" + repr(params) + return 'default:' + repr(params) @cherrypy.expose def other(self): - return "other" + return 'other' @cherrypy.expose def extra(self, *p): @@ -38,11 +38,11 @@ class ObjectMappingTest(helper.CPWebCase): raise cherrypy.HTTPRedirect('dir1/', 302) def notExposed(self): - return "not exposed" + return 'not exposed' @cherrypy.expose def confvalue(self): - return cherrypy.request.config.get("user") + return cherrypy.request.config.get('user') @cherrypy.expose def redirect_via_url(self, path): @@ -50,50 +50,50 @@ class ObjectMappingTest(helper.CPWebCase): @cherrypy.expose def translate_html(self): - return "OK" + return 'OK' @cherrypy.expose def mapped_func(self, ID=None): - return "ID is %s" % ID - setattr(Root, "Von B\xfclow", mapped_func) + return 'ID is %s' % ID + setattr(Root, 'Von B\xfclow', mapped_func) class Exposing: @cherrypy.expose def base(self): - return "expose works!" - cherrypy.expose(base, "1") - cherrypy.expose(base, "2") + return 'expose works!' + cherrypy.expose(base, '1') + cherrypy.expose(base, '2') class ExposingNewStyle(object): @cherrypy.expose def base(self): - return "expose works!" - cherrypy.expose(base, "1") - cherrypy.expose(base, "2") + return 'expose works!' + cherrypy.expose(base, '1') + cherrypy.expose(base, '2') class Dir1: @cherrypy.expose def index(self): - return "index for dir1" + return 'index for dir1' @cherrypy.expose @cherrypy.config(**{'tools.trailing_slash.extra': True}) def myMethod(self): - return "myMethod from dir1, path_info is:" + repr( + return 'myMethod from dir1, path_info is:' + repr( cherrypy.request.path_info) @cherrypy.expose def default(self, *params): - return "default for dir1, param is:" + repr(params) + return 'default for dir1, param is:' + repr(params) class Dir2: @cherrypy.expose def index(self): - return "index for dir2, path is:" + cherrypy.request.path_info + return 'index for dir2, path is:' + cherrypy.request.path_info @cherrypy.expose def script_name(self): @@ -101,27 +101,27 @@ class ObjectMappingTest(helper.CPWebCase): @cherrypy.expose def cherrypy_url(self): - return cherrypy.url("/extra") + return cherrypy.url('/extra') @cherrypy.expose def posparam(self, *vpath): - return "/".join(vpath) + return '/'.join(vpath) class Dir3: def default(self): - return "default for dir3, not exposed" + return 'default for dir3, not exposed' class Dir4: def index(self): - return "index for dir4, not exposed" + return 'index for dir4, not exposed' class DefNoIndex: @cherrypy.expose def default(self, *args): - raise cherrypy.HTTPRedirect("contact") + raise cherrypy.HTTPRedirect('contact') # MethodDispatcher code @cherrypy.expose @@ -151,7 +151,7 @@ class ObjectMappingTest(helper.CPWebCase): d = cherrypy.dispatch.MethodDispatcher() for url in script_names: - conf = {'/': {'user': (url or "/").split("/")[-2]}, + conf = {'/': {'user': (url or '/').split('/')[-2]}, '/bymethod': {'request.dispatch': d}, '/collection': {'request.dispatch': d}, } @@ -161,17 +161,17 @@ class ObjectMappingTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "made it!" + return 'made it!' - cherrypy.tree.mount(Isolated(), "/isolated") + cherrypy.tree.mount(Isolated(), '/isolated') @cherrypy.expose class AnotherApp: def GET(self): - return "milk" + return 'milk' - cherrypy.tree.mount(AnotherApp(), "/app", + cherrypy.tree.mount(AnotherApp(), '/app', {'/': {'request.dispatch': d}}) def testObjectMapping(self): @@ -181,82 +181,82 @@ class ObjectMappingTest(helper.CPWebCase): self.getPage('/') self.assertBody('world') - self.getPage("/dir1/myMethod") + self.getPage('/dir1/myMethod') self.assertBody( "myMethod from dir1, path_info is:'/dir1/myMethod'") - self.getPage("/this/method/does/not/exist") + self.getPage('/this/method/does/not/exist') self.assertBody( "default:('this', 'method', 'does', 'not', 'exist')") - self.getPage("/extra/too/much") + self.getPage('/extra/too/much') self.assertBody("('too', 'much')") - self.getPage("/other") + self.getPage('/other') self.assertBody('other') - self.getPage("/notExposed") + self.getPage('/notExposed') self.assertBody("default:('notExposed',)") - self.getPage("/dir1/dir2/") + self.getPage('/dir1/dir2/') self.assertBody('index for dir2, path is:/dir1/dir2/') # Test omitted trailing slash (should be redirected by default). - self.getPage("/dir1/dir2") + self.getPage('/dir1/dir2') self.assertStatus(301) self.assertHeader('Location', '%s/dir1/dir2/' % self.base()) # Test extra trailing slash (should be redirected if configured). - self.getPage("/dir1/myMethod/") + self.getPage('/dir1/myMethod/') self.assertStatus(301) self.assertHeader('Location', '%s/dir1/myMethod' % self.base()) # Test that default method must be exposed in order to match. - self.getPage("/dir1/dir2/dir3/dir4/index") + self.getPage('/dir1/dir2/dir3/dir4/index') self.assertBody( "default for dir1, param is:('dir2', 'dir3', 'dir4', 'index')") # Test *vpath when default() is defined but not index() # This also tests HTTPRedirect with default. - self.getPage("/defnoindex") + self.getPage('/defnoindex') self.assertStatus((302, 303)) self.assertHeader('Location', '%s/contact' % self.base()) - self.getPage("/defnoindex/") + self.getPage('/defnoindex/') self.assertStatus((302, 303)) self.assertHeader('Location', '%s/defnoindex/contact' % self.base()) - self.getPage("/defnoindex/page") + self.getPage('/defnoindex/page') self.assertStatus((302, 303)) self.assertHeader('Location', '%s/defnoindex/contact' % self.base()) - self.getPage("/redirect") + self.getPage('/redirect') self.assertStatus('302 Found') self.assertHeader('Location', '%s/dir1/' % self.base()) - if not getattr(cherrypy.server, "using_apache", False): + if not getattr(cherrypy.server, 'using_apache', False): # Test that we can use URL's which aren't all valid Python # identifiers # This should also test the %XX-unquoting of URL's. - self.getPage("/Von%20B%fclow?ID=14") - self.assertBody("ID is 14") + self.getPage('/Von%20B%fclow?ID=14') + self.assertBody('ID is 14') # Test that %2F in the path doesn't get unquoted too early; # that is, it should not be used to separate path components. # See ticket #393. - self.getPage("/page%2Fname") + self.getPage('/page%2Fname') self.assertBody("default:('page/name',)") - self.getPage("/dir1/dir2/script_name") + self.getPage('/dir1/dir2/script_name') self.assertBody(url) - self.getPage("/dir1/dir2/cherrypy_url") - self.assertBody("%s/extra" % self.base()) + self.getPage('/dir1/dir2/cherrypy_url') + self.assertBody('%s/extra' % self.base()) # Test that configs don't overwrite each other from diferent apps - self.getPage("/confvalue") - self.assertBody((url or "/").split("/")[-2]) + self.getPage('/confvalue') + self.assertBody((url or '/').split('/')[-2]) - self.script_name = "" + self.script_name = '' # Test absoluteURI's in the Request-Line self.getPage('http://%s:%s/' % (self.interface(), self.PORT)) @@ -272,30 +272,30 @@ class ObjectMappingTest(helper.CPWebCase): # Test that the "isolated" app doesn't leak url's into the root app. # If it did leak, Root.default() would answer with # "default:('isolated', 'doesnt', 'exist')". - self.getPage("/isolated/") - self.assertStatus("200 OK") - self.assertBody("made it!") - self.getPage("/isolated/doesnt/exist") - self.assertStatus("404 Not Found") + self.getPage('/isolated/') + self.assertStatus('200 OK') + self.assertBody('made it!') + self.getPage('/isolated/doesnt/exist') + self.assertStatus('404 Not Found') # Make sure /foobar maps to Root.foobar and not to the app # mounted at /foo. See # https://github.com/cherrypy/cherrypy/issues/573 - self.getPage("/foobar") - self.assertBody("bar") + self.getPage('/foobar') + self.assertBody('bar') def test_translate(self): - self.getPage("/translate_html") - self.assertStatus("200 OK") - self.assertBody("OK") + self.getPage('/translate_html') + self.assertStatus('200 OK') + self.assertBody('OK') - self.getPage("/translate.html") - self.assertStatus("200 OK") - self.assertBody("OK") + self.getPage('/translate.html') + self.assertStatus('200 OK') + self.assertBody('OK') - self.getPage("/translate-html") - self.assertStatus("200 OK") - self.assertBody("OK") + self.getPage('/translate-html') + self.assertStatus('200 OK') + self.assertBody('OK') def test_redir_using_url(self): for url in script_names: @@ -322,75 +322,75 @@ class ObjectMappingTest(helper.CPWebCase): self.assertHeader('Location', '%s/' % self.base()) def testPositionalParams(self): - self.getPage("/dir1/dir2/posparam/18/24/hut/hike") - self.assertBody("18/24/hut/hike") + self.getPage('/dir1/dir2/posparam/18/24/hut/hike') + self.assertBody('18/24/hut/hike') # intermediate index methods should not receive posparams; # only the "final" index method should do so. - self.getPage("/dir1/dir2/5/3/sir") + self.getPage('/dir1/dir2/5/3/sir') self.assertBody("default for dir1, param is:('dir2', '5', '3', 'sir')") # test that extra positional args raises an 404 Not Found # See https://github.com/cherrypy/cherrypy/issues/733. - self.getPage("/dir1/dir2/script_name/extra/stuff") + self.getPage('/dir1/dir2/script_name/extra/stuff') self.assertStatus(404) def testExpose(self): # Test the cherrypy.expose function/decorator - self.getPage("/exposing/base") - self.assertBody("expose works!") + self.getPage('/exposing/base') + self.assertBody('expose works!') - self.getPage("/exposing/1") - self.assertBody("expose works!") + self.getPage('/exposing/1') + self.assertBody('expose works!') - self.getPage("/exposing/2") - self.assertBody("expose works!") + self.getPage('/exposing/2') + self.assertBody('expose works!') - self.getPage("/exposingnew/base") - self.assertBody("expose works!") + self.getPage('/exposingnew/base') + self.assertBody('expose works!') - self.getPage("/exposingnew/1") - self.assertBody("expose works!") + self.getPage('/exposingnew/1') + self.assertBody('expose works!') - self.getPage("/exposingnew/2") - self.assertBody("expose works!") + self.getPage('/exposingnew/2') + self.assertBody('expose works!') def testMethodDispatch(self): - self.getPage("/bymethod") + self.getPage('/bymethod') self.assertBody("['another']") self.assertHeader('Allow', 'GET, HEAD, POST') - self.getPage("/bymethod", method="HEAD") - self.assertBody("") + self.getPage('/bymethod', method='HEAD') + self.assertBody('') self.assertHeader('Allow', 'GET, HEAD, POST') - self.getPage("/bymethod", method="POST", body="thing=one") - self.assertBody("") + self.getPage('/bymethod', method='POST', body='thing=one') + self.assertBody('') self.assertHeader('Allow', 'GET, HEAD, POST') - self.getPage("/bymethod") + self.getPage('/bymethod') self.assertBody(repr(['another', ntou('one')])) self.assertHeader('Allow', 'GET, HEAD, POST') - self.getPage("/bymethod", method="PUT") + self.getPage('/bymethod', method='PUT') self.assertErrorPage(405) self.assertHeader('Allow', 'GET, HEAD, POST') # Test default with posparams - self.getPage("/collection/silly", method="POST") - self.getPage("/collection", method="GET") + self.getPage('/collection/silly', method='POST') + self.getPage('/collection', method='GET') self.assertBody("['a', 'bit', 'silly']") # Test custom dispatcher set on app root (see #737). - self.getPage("/app") - self.assertBody("milk") + self.getPage('/app') + self.assertBody('milk') def testTreeMounting(self): class Root(object): @cherrypy.expose def hello(self): - return "Hello world!" + return 'Hello world!' # When mounting an application instance, # we can't specify a different script name in the call to mount. @@ -417,7 +417,7 @@ class ObjectMappingTest(helper.CPWebCase): def testKeywords(self): if sys.version_info < (3,): - return self.skip("skipped (Python 3 only)") + return self.skip('skipped (Python 3 only)') exec("""class Root(object): @cherrypy.expose def hello(self, *, name='world'): diff --git a/cherrypy/test/test_params.py b/cherrypy/test/test_params.py index bb13da16..f40de030 100644 --- a/cherrypy/test/test_params.py +++ b/cherrypy/test/test_params.py @@ -43,7 +43,7 @@ class ParamsTest(helper.CPWebCase): def test_syntax(self): if sys.version_info < (3,): - return self.skip("skipped (Python 3 only)") + return self.skip('skipped (Python 3 only)') code = textwrap.dedent(""" class Root: @cherrypy.expose diff --git a/cherrypy/test/test_proxy.py b/cherrypy/test/test_proxy.py index 8e434d15..cf35a216 100644 --- a/cherrypy/test/test_proxy.py +++ b/cherrypy/test/test_proxy.py @@ -1,7 +1,7 @@ import cherrypy from cherrypy.test import helper -script_names = ["", "/path/to/myapp"] +script_names = ['', '/path/to/myapp'] class ProxyTest(helper.CPWebCase): @@ -22,7 +22,7 @@ class ProxyTest(helper.CPWebCase): def __init__(self, sn): # Calculate a URL outside of any requests. self.thisnewpage = cherrypy.url( - "/this/new/page", script_name=sn) + '/this/new/page', script_name=sn) @cherrypy.expose def pageurl(self): @@ -56,83 +56,83 @@ class ProxyTest(helper.CPWebCase): @cherrypy.expose def newurl(self): return ("Browse to <a href='%s'>this page</a>." - % cherrypy.url("/this/new/page")) + % cherrypy.url('/this/new/page')) for sn in script_names: cherrypy.tree.mount(Root(sn), sn) def testProxy(self): - self.getPage("/") + self.getPage('/') self.assertHeader('Location', - "%s://www.mydomain.test%s/dummy" % + '%s://www.mydomain.test%s/dummy' % (self.scheme, self.prefix())) # Test X-Forwarded-Host (Apache 1.3.33+ and Apache 2) self.getPage( - "/", headers=[('X-Forwarded-Host', 'http://www.example.test')]) - self.assertHeader('Location', "http://www.example.test/dummy") - self.getPage("/", headers=[('X-Forwarded-Host', 'www.example.test')]) - self.assertHeader('Location', "%s://www.example.test/dummy" % + '/', headers=[('X-Forwarded-Host', 'http://www.example.test')]) + self.assertHeader('Location', 'http://www.example.test/dummy') + self.getPage('/', headers=[('X-Forwarded-Host', 'www.example.test')]) + self.assertHeader('Location', '%s://www.example.test/dummy' % self.scheme) # Test multiple X-Forwarded-Host headers - self.getPage("/", headers=[ + self.getPage('/', headers=[ ('X-Forwarded-Host', 'http://www.example.test, www.cherrypy.test'), ]) - self.assertHeader('Location', "http://www.example.test/dummy") + self.assertHeader('Location', 'http://www.example.test/dummy') # Test X-Forwarded-For (Apache2) - self.getPage("/remoteip", + self.getPage('/remoteip', headers=[('X-Forwarded-For', '192.168.0.20')]) - self.assertBody("192.168.0.20") + self.assertBody('192.168.0.20') #Fix bug #1268 - self.getPage("/remoteip", + self.getPage('/remoteip', headers=[ ('X-Forwarded-For', '67.15.36.43, 192.168.0.20') ]) - self.assertBody("67.15.36.43") + self.assertBody('67.15.36.43') # Test X-Host (lighttpd; see https://trac.lighttpd.net/trac/ticket/418) - self.getPage("/xhost", headers=[('X-Host', 'www.example.test')]) - self.assertHeader('Location', "%s://www.example.test/blah" % + self.getPage('/xhost', headers=[('X-Host', 'www.example.test')]) + self.assertHeader('Location', '%s://www.example.test/blah' % self.scheme) # Test X-Forwarded-Proto (lighttpd) - self.getPage("/base", headers=[('X-Forwarded-Proto', 'https')]) - self.assertBody("https://www.mydomain.test") + self.getPage('/base', headers=[('X-Forwarded-Proto', 'https')]) + self.assertBody('https://www.mydomain.test') # Test X-Forwarded-Ssl (webfaction?) - self.getPage("/ssl", headers=[('X-Forwarded-Ssl', 'on')]) - self.assertBody("https://www.mydomain.test") + self.getPage('/ssl', headers=[('X-Forwarded-Ssl', 'on')]) + self.assertBody('https://www.mydomain.test') # Test cherrypy.url() for sn in script_names: # Test the value inside requests - self.getPage(sn + "/newurl") + self.getPage(sn + '/newurl') self.assertBody( "Browse to <a href='%s://www.mydomain.test" % self.scheme + sn + "/this/new/page'>this page</a>.") - self.getPage(sn + "/newurl", headers=[('X-Forwarded-Host', + self.getPage(sn + '/newurl', headers=[('X-Forwarded-Host', 'http://www.example.test')]) self.assertBody("Browse to <a href='http://www.example.test" + sn + "/this/new/page'>this page</a>.") # Test the value outside requests - port = "" - if self.scheme == "http" and self.PORT != 80: - port = ":%s" % self.PORT - elif self.scheme == "https" and self.PORT != 443: - port = ":%s" % self.PORT + port = '' + if self.scheme == 'http' and self.PORT != 80: + port = ':%s' % self.PORT + elif self.scheme == 'https' and self.PORT != 443: + port = ':%s' % self.PORT host = self.HOST if host in ('0.0.0.0', '::'): import socket host = socket.gethostname() - expected = ("%s://%s%s%s/this/new/page" + expected = ('%s://%s%s%s/this/new/page' % (self.scheme, host, port, sn)) - self.getPage(sn + "/pageurl") + self.getPage(sn + '/pageurl') self.assertBody(expected) # Test trailing slash (see # https://github.com/cherrypy/cherrypy/issues/562). - self.getPage("/xhost/", headers=[('X-Host', 'www.example.test')]) - self.assertHeader('Location', "%s://www.example.test/xhost" + self.getPage('/xhost/', headers=[('X-Host', 'www.example.test')]) + self.assertHeader('Location', '%s://www.example.test/xhost' % self.scheme) diff --git a/cherrypy/test/test_refleaks.py b/cherrypy/test/test_refleaks.py index a6249e0d..659ea99c 100644 --- a/cherrypy/test/test_refleaks.py +++ b/cherrypy/test/test_refleaks.py @@ -22,13 +22,13 @@ class ReferenceTests(helper.CPWebCase): @cherrypy.expose def index(self, *args, **kwargs): cherrypy.request.thing = data - return "Hello world!" + return 'Hello world!' cherrypy.tree.mount(Root()) def test_threadlocal_garbage(self): if platform.system() == 'Darwin': - self.skip("queue issues; see #1474") + self.skip('queue issues; see #1474') success = itertools.count() def getpage(): @@ -43,7 +43,7 @@ class ReferenceTests(helper.CPWebCase): response = c.getresponse() body = response.read() self.assertEqual(response.status, 200) - self.assertEqual(body, b"Hello world!") + self.assertEqual(body, b'Hello world!') finally: c.close() next(success) diff --git a/cherrypy/test/test_request_obj.py b/cherrypy/test/test_request_obj.py index ed6bfe8c..0af4ec81 100644 --- a/cherrypy/test/test_request_obj.py +++ b/cherrypy/test/test_request_obj.py @@ -13,8 +13,8 @@ from cherrypy.test import helper localDir = os.path.dirname(__file__) -defined_http_methods = ("OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", - "TRACE", "PROPFIND") +defined_http_methods = ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', + 'TRACE', 'PROPFIND') # Client-side code # @@ -28,7 +28,7 @@ class RequestObjectTests(helper.CPWebCase): @cherrypy.expose def index(self): - return "hello" + return 'hello' @cherrypy.expose def scheme(self): @@ -60,57 +60,57 @@ class RequestObjectTests(helper.CPWebCase): return repr(thing) def ismap(self, x, y): - return "Coordinates: %s, %s" % (x, y) + return 'Coordinates: %s, %s' % (x, y) @cherrypy.config(**{'request.query_string_encoding': 'latin1'}) def default(self, *args, **kwargs): - return "args: %s kwargs: %s" % (args, sorted(kwargs.items())) + return 'args: %s kwargs: %s' % (args, sorted(kwargs.items())) @cherrypy.expose class ParamErrorsCallable(object): def __call__(self): - return "data" + return 'data' class ParamErrors(Test): @cherrypy.expose def one_positional(self, param1): - return "data" + return 'data' @cherrypy.expose def one_positional_args(self, param1, *args): - return "data" + return 'data' @cherrypy.expose def one_positional_args_kwargs(self, param1, *args, **kwargs): - return "data" + return 'data' @cherrypy.expose def one_positional_kwargs(self, param1, **kwargs): - return "data" + return 'data' @cherrypy.expose def no_positional(self): - return "data" + return 'data' @cherrypy.expose def no_positional_args(self, *args): - return "data" + return 'data' @cherrypy.expose def no_positional_args_kwargs(self, *args, **kwargs): - return "data" + return 'data' @cherrypy.expose def no_positional_kwargs(self, **kwargs): - return "data" + return 'data' callable_object = ParamErrorsCallable() @cherrypy.expose def raise_type_error(self, **kwargs): - raise TypeError("Client Error") + raise TypeError('Client Error') @cherrypy.expose def raise_type_error_with_default_param(self, x, y=None): @@ -127,12 +127,12 @@ class RequestObjectTests(helper.CPWebCase): raise cherrypy.HTTPError("410 Gone fishin'") @cherrypy.config(**{ - 'error_page.404': os.path.join(localDir, "static/index.html"), + 'error_page.404': os.path.join(localDir, 'static/index.html'), 'error_page.401': callable_error_page, }) def custom(self, err='404'): raise cherrypy.HTTPError( - int(err), "No, <b>really</b>, not found!") + int(err), 'No, <b>really</b>, not found!') @cherrypy.config(**{ 'error_page.default': callable_error_page, @@ -140,27 +140,27 @@ class RequestObjectTests(helper.CPWebCase): def custom_default(self): return 1 + 'a' # raise an unexpected error - @cherrypy.config(**{'error_page.404': "nonexistent.html"}) + @cherrypy.config(**{'error_page.404': 'nonexistent.html'}) def noexist(self): - raise cherrypy.HTTPError(404, "No, <b>really</b>, not found!") + raise cherrypy.HTTPError(404, 'No, <b>really</b>, not found!') def page_method(self): raise ValueError() def page_yield(self): - yield "howdy" + yield 'howdy' raise ValueError() - @cherrypy.config(**{"response.stream": True}) + @cherrypy.config(**{'response.stream': True}) def page_streamed(self): - yield "word up" + yield 'word up' raise ValueError() - yield "very oops" + yield 'very oops' @cherrypy.config(**{'request.show_tracebacks': False}) def cause_err_in_finalize(self): # Since status must start with an int, this should error. - cherrypy.response.status = "ZOO OK" + cherrypy.response.status = 'ZOO OK' @cherrypy.config(**{'request.throw_errors': True}) def rethrow(self): @@ -172,7 +172,7 @@ class RequestObjectTests(helper.CPWebCase): class Expect(Test): def expectation_failed(self): - expect = cherrypy.request.headers.elements("Expect") + expect = cherrypy.request.headers.elements('Expect') if expect and expect[0].value != '100-continue': raise cherrypy.HTTPError(400) raise cherrypy.HTTPError(417, 'Expectation Failed') @@ -192,7 +192,7 @@ class RequestObjectTests(helper.CPWebCase): # Set the most common headers hMap = cherrypy.response.headers - hMap['content-type'] = "text/html" + hMap['content-type'] = 'text/html' hMap['content-length'] = 18 hMap['server'] = 'CherryPy headertest' hMap['location'] = ('%s://%s:%s/headers/' @@ -203,7 +203,7 @@ class RequestObjectTests(helper.CPWebCase): # Set a rare header for fun hMap['Expires'] = 'Thu, 01 Dec 2194 16:00:00 GMT' - return "double header test" + return 'double header test' def ifmatch(self): val = cherrypy.request.headers['If-Match'] @@ -215,16 +215,16 @@ 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([six.text_type(x) for x in e]) class Method(Test): def index(self): m = cherrypy.request.method - if m in defined_http_methods or m == "CONNECT": + if m in defined_http_methods or m == 'CONNECT': return m - if m == "LINK": + if m == 'LINK': raise cherrypy.HTTPError(405) else: raise cherrypy.HTTPError(501) @@ -238,7 +238,7 @@ class RequestObjectTests(helper.CPWebCase): return cherrypy.request.body def reachable(self): - return "success" + return 'success' class Divorce: @@ -256,89 +256,89 @@ class RequestObjectTests(helper.CPWebCase): @cherrypy.expose def index(self): - yield "<h1>Choose your document</h1>\n" - yield "<ul>\n" + yield '<h1>Choose your document</h1>\n' + yield '<ul>\n' for id, contents in self.documents.items(): yield ( " <li><a href='/divorce/get?ID=%s'>%s</a>:" - " %s</li>\n" % (id, id, contents)) - yield "</ul>" + ' %s</li>\n' % (id, id, contents)) + yield '</ul>' @cherrypy.expose def get(self, ID): - return ("Divorce document %s: %s" % - (ID, self.documents.get(ID, "empty"))) + return ('Divorce document %s: %s' % + (ID, self.documents.get(ID, 'empty'))) root.divorce = Divorce() class ThreadLocal(Test): def index(self): - existing = repr(getattr(cherrypy.request, "asdf", None)) - cherrypy.request.asdf = "rassfrassin" + existing = repr(getattr(cherrypy.request, 'asdf', None)) + cherrypy.request.asdf = 'rassfrassin' return existing appconf = { '/method': { - 'request.methods_with_bodies': ("POST", "PUT", "PROPFIND") + 'request.methods_with_bodies': ('POST', 'PUT', 'PROPFIND') }, } cherrypy.tree.mount(root, config=appconf) def test_scheme(self): - self.getPage("/scheme") + self.getPage('/scheme') self.assertBody(self.scheme) def testRelativeURIPathInfo(self): - self.getPage("/pathinfo/foo/bar") - self.assertBody("/pathinfo/foo/bar") + self.getPage('/pathinfo/foo/bar') + self.assertBody('/pathinfo/foo/bar') def testAbsoluteURIPathInfo(self): # http://cherrypy.org/ticket/1061 - self.getPage("http://localhost/pathinfo/foo/bar") - self.assertBody("/pathinfo/foo/bar") + self.getPage('http://localhost/pathinfo/foo/bar') + self.assertBody('/pathinfo/foo/bar') def testParams(self): - self.getPage("/params/?thing=a") - self.assertBody(repr(ntou("a"))) + self.getPage('/params/?thing=a') + self.assertBody(repr(ntou('a'))) - self.getPage("/params/?thing=a&thing=b&thing=c") + self.getPage('/params/?thing=a&thing=b&thing=c') self.assertBody(repr([ntou('a'), ntou('b'), ntou('c')])) # Test friendly error message when given params are not accepted. - cherrypy.config.update({"request.show_mismatched_params": True}) - self.getPage("/params/?notathing=meeting") - self.assertInBody("Missing parameters: thing") - self.getPage("/params/?thing=meeting¬athing=meeting") - self.assertInBody("Unexpected query string parameters: notathing") + cherrypy.config.update({'request.show_mismatched_params': True}) + self.getPage('/params/?notathing=meeting') + self.assertInBody('Missing parameters: thing') + self.getPage('/params/?thing=meeting¬athing=meeting') + self.assertInBody('Unexpected query string parameters: notathing') # Test ability to turn off friendly error messages - cherrypy.config.update({"request.show_mismatched_params": False}) - self.getPage("/params/?notathing=meeting") - self.assertInBody("Not Found") - self.getPage("/params/?thing=meeting¬athing=meeting") - self.assertInBody("Not Found") + cherrypy.config.update({'request.show_mismatched_params': False}) + self.getPage('/params/?notathing=meeting') + self.assertInBody('Not Found') + self.getPage('/params/?thing=meeting¬athing=meeting') + self.assertInBody('Not Found') # Test "% HEX HEX"-encoded URL, param keys, and values - self.getPage("/params/%d4%20%e3/cheese?Gruy%E8re=Bulgn%e9ville") - self.assertBody("args: %s kwargs: %s" % + self.getPage('/params/%d4%20%e3/cheese?Gruy%E8re=Bulgn%e9ville') + self.assertBody('args: %s kwargs: %s' % (('\xd4 \xe3', 'cheese'), [('Gruy\xe8re', ntou('Bulgn\xe9ville'))])) # Make sure that encoded = and & get parsed correctly self.getPage( - "/params/code?url=http%3A//cherrypy.org/index%3Fa%3D1%26b%3D2") - self.assertBody("args: %s kwargs: %s" % + '/params/code?url=http%3A//cherrypy.org/index%3Fa%3D1%26b%3D2') + self.assertBody('args: %s kwargs: %s' % (('code',), [('url', ntou('http://cherrypy.org/index?a=1&b=2'))])) # Test coordinates sent by <img ismap> - self.getPage("/params/ismap?223,114") - self.assertBody("Coordinates: 223, 114") + self.getPage('/params/ismap?223,114') + self.assertBody('Coordinates: 223, 114') # Test "name[key]" dict-like params - self.getPage("/params/dictlike?a[1]=1&a[2]=2&b=foo&b[bar]=baz") - self.assertBody("args: %s kwargs: %s" % + self.getPage('/params/dictlike?a[1]=1&a[2]=2&b=foo&b[bar]=baz') + self.assertBody('args: %s kwargs: %s' % (('dictlike',), [('a[1]', ntou('1')), ('a[2]', ntou('2')), ('b', ntou('foo')), ('b[bar]', ntou('baz'))])) @@ -430,7 +430,7 @@ class RequestObjectTests(helper.CPWebCase): if show_mismatched_params: self.assertInBody(msg) else: - self.assertInBody("Not Found") + self.assertInBody('Not Found') # if body parameters are wrong, a 400 must be returned. for uri, body, msg in ( @@ -459,7 +459,7 @@ class RequestObjectTests(helper.CPWebCase): if show_mismatched_params: self.assertInBody(msg) else: - self.assertInBody("400 Bad") + self.assertInBody('400 Bad') # even if body parameters are wrong, if we get the uri wrong, then # it's a 404 @@ -487,7 +487,7 @@ class RequestObjectTests(helper.CPWebCase): if show_mismatched_params: self.assertInBody(msg) else: - self.assertInBody("Not Found") + self.assertInBody('Not Found') # In the case that a handler raises a TypeError we should # let that type error through. @@ -501,7 +501,7 @@ class RequestObjectTests(helper.CPWebCase): self.assertTrue('Client Error', self.body) def testErrorHandling(self): - self.getPage("/error/missing") + self.getPage('/error/missing') self.assertStatus(404) self.assertErrorPage(404, "The path '/error/missing' was not found.") @@ -509,27 +509,27 @@ class RequestObjectTests(helper.CPWebCase): ignore.append(ValueError) try: valerr = '\n raise ValueError()\nValueError' - self.getPage("/error/page_method") + self.getPage('/error/page_method') self.assertErrorPage(500, pattern=valerr) - self.getPage("/error/page_yield") + self.getPage('/error/page_yield') self.assertErrorPage(500, pattern=valerr) - if (cherrypy.server.protocol_version == "HTTP/1.0" or - getattr(cherrypy.server, "using_apache", False)): - self.getPage("/error/page_streamed") + if (cherrypy.server.protocol_version == 'HTTP/1.0' or + getattr(cherrypy.server, 'using_apache', False)): + self.getPage('/error/page_streamed') # Because this error is raised after the response body has # started, the status should not change to an error status. self.assertStatus(200) - self.assertBody("word up") + self.assertBody('word up') else: # Under HTTP/1.1, the chunked transfer-coding is used. # The HTTP client will choke when the output is incomplete. self.assertRaises((ValueError, IncompleteRead), self.getPage, - "/error/page_streamed") + '/error/page_streamed') # No traceback should be present - self.getPage("/error/cause_err_in_finalize") + self.getPage('/error/cause_err_in_finalize') msg = "Illegal response status from server ('ZOO' is non-numeric)." self.assertErrorPage(500, msg, None) finally: @@ -540,126 +540,126 @@ class RequestObjectTests(helper.CPWebCase): self.assertStatus("410 Gone fishin'") # Test custom error page for a specific error. - self.getPage("/error/custom") + self.getPage('/error/custom') self.assertStatus(404) - self.assertBody("Hello, world\r\n" + (" " * 499)) + self.assertBody('Hello, world\r\n' + (' ' * 499)) # Test custom error page for a specific error. - self.getPage("/error/custom?err=401") + self.getPage('/error/custom?err=401') self.assertStatus(401) self.assertBody( - "Error 401 Unauthorized - " + 'Error 401 Unauthorized - ' "Well, I'm very sorry but you haven't paid!") # Test default custom error page. - self.getPage("/error/custom_default") + self.getPage('/error/custom_default') self.assertStatus(500) self.assertBody( - "Error 500 Internal Server Error - " + 'Error 500 Internal Server Error - ' "Well, I'm very sorry but you haven't paid!".ljust(513)) # Test error in custom error page (ticket #305). # Note that the message is escaped for HTML (ticket #310). - self.getPage("/error/noexist") + self.getPage('/error/noexist') self.assertStatus(404) if sys.version_info >= (3, 3): - exc_name = "FileNotFoundError" + exc_name = 'FileNotFoundError' else: - exc_name = "IOError" - msg = ("No, <b>really</b>, not found!<br />" - "In addition, the custom error page failed:\n<br />" - "%s: [Errno 2] " + exc_name = 'IOError' + msg = ('No, <b>really</b>, not found!<br />' + 'In addition, the custom error page failed:\n<br />' + '%s: [Errno 2] ' "No such file or directory: 'nonexistent.html'") % (exc_name,) self.assertInBody(msg) - if getattr(cherrypy.server, "using_apache", False): + if getattr(cherrypy.server, 'using_apache', False): pass else: # Test throw_errors (ticket #186). - self.getPage("/error/rethrow") - self.assertInBody("raise ValueError()") + self.getPage('/error/rethrow') + self.assertInBody('raise ValueError()') def testExpect(self): e = ('Expect', '100-continue') - self.getPage("/headerelements/get_elements?headername=Expect", [e]) + self.getPage('/headerelements/get_elements?headername=Expect', [e]) self.assertBody('100-continue') - self.getPage("/expect/expectation_failed", [e]) + self.getPage('/expect/expectation_failed', [e]) self.assertStatus(417) def testHeaderElements(self): # Accept-* header elements should be sorted, with most preferred first. h = [('Accept', 'audio/*; q=0.2, audio/basic')] - self.getPage("/headerelements/get_elements?headername=Accept", h) + self.getPage('/headerelements/get_elements?headername=Accept', h) self.assertStatus(200) - self.assertBody("audio/basic\n" - "audio/*;q=0.2") + self.assertBody('audio/basic\n' + 'audio/*;q=0.2') h = [ ('Accept', 'text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c') ] - self.getPage("/headerelements/get_elements?headername=Accept", h) + self.getPage('/headerelements/get_elements?headername=Accept', h) self.assertStatus(200) - self.assertBody("text/x-c\n" - "text/html\n" - "text/x-dvi;q=0.8\n" - "text/plain;q=0.5") + self.assertBody('text/x-c\n' + 'text/html\n' + 'text/x-dvi;q=0.8\n' + 'text/plain;q=0.5') # Test that more specific media ranges get priority. h = [('Accept', 'text/*, text/html, text/html;level=1, */*')] - self.getPage("/headerelements/get_elements?headername=Accept", h) + self.getPage('/headerelements/get_elements?headername=Accept', h) self.assertStatus(200) - self.assertBody("text/html;level=1\n" - "text/html\n" - "text/*\n" - "*/*") + self.assertBody('text/html;level=1\n' + 'text/html\n' + 'text/*\n' + '*/*') # Test Accept-Charset h = [('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8')] self.getPage( - "/headerelements/get_elements?headername=Accept-Charset", h) - self.assertStatus("200 OK") - self.assertBody("iso-8859-5\n" - "unicode-1-1;q=0.8") + '/headerelements/get_elements?headername=Accept-Charset', h) + self.assertStatus('200 OK') + self.assertBody('iso-8859-5\n' + 'unicode-1-1;q=0.8') # Test Accept-Encoding h = [('Accept-Encoding', 'gzip;q=1.0, identity; q=0.5, *;q=0')] self.getPage( - "/headerelements/get_elements?headername=Accept-Encoding", h) - self.assertStatus("200 OK") - self.assertBody("gzip;q=1.0\n" - "identity;q=0.5\n" - "*;q=0") + '/headerelements/get_elements?headername=Accept-Encoding', h) + self.assertStatus('200 OK') + self.assertBody('gzip;q=1.0\n' + 'identity;q=0.5\n' + '*;q=0') # Test Accept-Language h = [('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7')] self.getPage( - "/headerelements/get_elements?headername=Accept-Language", h) - self.assertStatus("200 OK") - self.assertBody("da\n" - "en-gb;q=0.8\n" - "en;q=0.7") + '/headerelements/get_elements?headername=Accept-Language', h) + self.assertStatus('200 OK') + self.assertBody('da\n' + 'en-gb;q=0.8\n' + 'en;q=0.7') # Test malformed header parsing. See # https://github.com/cherrypy/cherrypy/issues/763. - self.getPage("/headerelements/get_elements?headername=Content-Type", + self.getPage('/headerelements/get_elements?headername=Content-Type', # Note the illegal trailing ";" headers=[('Content-Type', 'text/html; charset=utf-8;')]) self.assertStatus(200) - self.assertBody("text/html;charset=utf-8") + self.assertBody('text/html;charset=utf-8') def test_repeated_headers(self): # Test that two request headers are collapsed into one. # See https://github.com/cherrypy/cherrypy/issues/542. - self.getPage("/headers/Accept-Charset", - headers=[("Accept-Charset", "iso-8859-5"), - ("Accept-Charset", "unicode-1-1;q=0.8")]) - self.assertBody("iso-8859-5, unicode-1-1;q=0.8") + self.getPage('/headers/Accept-Charset', + headers=[('Accept-Charset', 'iso-8859-5'), + ('Accept-Charset', 'unicode-1-1;q=0.8')]) + self.assertBody('iso-8859-5, unicode-1-1;q=0.8') # Tests that each header only appears once, regardless of case. - self.getPage("/headers/doubledheaders") - self.assertBody("double header test") + self.getPage('/headers/doubledheaders') + self.assertBody('double header test') hnames = [name.title() for name, val in self.headers] for key in ['Content-Length', 'Content-Type', 'Date', 'Expires', 'Location', 'Server']: @@ -668,26 +668,26 @@ class RequestObjectTests(helper.CPWebCase): def test_encoded_headers(self): # First, make sure the innards work like expected. self.assertEqual( - httputil.decode_TEXT(ntou("=?utf-8?q?f=C3=BCr?=")), ntou("f\xfcr")) + httputil.decode_TEXT(ntou('=?utf-8?q?f=C3=BCr?=')), ntou('f\xfcr')) - if cherrypy.server.protocol_version == "HTTP/1.1": + if cherrypy.server.protocol_version == 'HTTP/1.1': # Test RFC-2047-encoded request and response header values u = ntou('\u212bngstr\xf6m', 'escape') - c = ntou("=E2=84=ABngstr=C3=B6m") - self.getPage("/headers/ifmatch", + c = ntou('=E2=84=ABngstr=C3=B6m') + self.getPage('/headers/ifmatch', [('If-Match', ntou('=?utf-8?q?%s?=') % c)]) # The body should be utf-8 encoded. - self.assertBody(ntob("\xe2\x84\xabngstr\xc3\xb6m")) + self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m')) # But the Etag header should be RFC-2047 encoded (binary) - self.assertHeader("ETag", ntou('=?utf-8?b?4oSrbmdzdHLDtm0=?=')) + self.assertHeader('ETag', ntou('=?utf-8?b?4oSrbmdzdHLDtm0=?=')) # Test a *LONG* RFC-2047-encoded request and response header value - self.getPage("/headers/ifmatch", + self.getPage('/headers/ifmatch', [('If-Match', ntou('=?utf-8?q?%s?=') % (c * 10))]) - self.assertBody(ntob("\xe2\x84\xabngstr\xc3\xb6m") * 10) + self.assertBody(ntob('\xe2\x84\xabngstr\xc3\xb6m') * 10) # Note: this is different output for Python3, but it decodes fine. etag = self.assertHeader( - "ETag", + 'ETag', '=?utf-8?b?4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt' '4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt' '4oSrbmdzdHLDtm3ihKtuZ3N0csO2beKEq25nc3Ryw7Zt' @@ -697,57 +697,57 @@ class RequestObjectTests(helper.CPWebCase): def test_header_presence(self): # If we don't pass a Content-Type header, it should not be present # in cherrypy.request.headers - self.getPage("/headers/Content-Type", + self.getPage('/headers/Content-Type', headers=[]) self.assertStatus(500) # If Content-Type is present in the request, it should be present in # cherrypy.request.headers - self.getPage("/headers/Content-Type", - headers=[("Content-type", "application/json")]) - self.assertBody("application/json") + self.getPage('/headers/Content-Type', + headers=[('Content-type', 'application/json')]) + self.assertBody('application/json') def test_basic_HTTPMethods(self): - helper.webtest.methods_with_bodies = ("POST", "PUT", "PROPFIND") + helper.webtest.methods_with_bodies = ('POST', 'PUT', 'PROPFIND') # Test that all defined HTTP methods work. for m in defined_http_methods: - self.getPage("/method/", method=m) + self.getPage('/method/', method=m) # HEAD requests should not return any body. - if m == "HEAD": - self.assertBody("") - elif m == "TRACE": + if m == 'HEAD': + self.assertBody('') + elif m == 'TRACE': # Some HTTP servers (like modpy) have their own TRACE support - self.assertEqual(self.body[:5], ntob("TRACE")) + self.assertEqual(self.body[:5], ntob('TRACE')) else: self.assertBody(m) # Request a PUT method with a form-urlencoded body - self.getPage("/method/parameterized", method="PUT", - body="data=on+top+of+other+things") - self.assertBody("on top of other things") + self.getPage('/method/parameterized', method='PUT', + body='data=on+top+of+other+things') + self.assertBody('on top of other things') # Request a PUT method with a file body - b = "one thing on top of another" - h = [("Content-Type", "text/plain"), - ("Content-Length", str(len(b)))] - self.getPage("/method/request_body", headers=h, method="PUT", body=b) + b = 'one thing on top of another' + h = [('Content-Type', 'text/plain'), + ('Content-Length', str(len(b)))] + self.getPage('/method/request_body', headers=h, method='PUT', body=b) self.assertStatus(200) self.assertBody(b) # Request a PUT method with a file body but no Content-Type. # See https://github.com/cherrypy/cherrypy/issues/790. - b = ntob("one thing on top of another") + b = ntob('one thing on top of another') self.persistent = True try: conn = self.HTTP_CONN - conn.putrequest("PUT", "/method/request_body", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('PUT', '/method/request_body', skip_host=True) + conn.putheader('Host', self.HOST) conn.putheader('Content-Length', str(len(b))) conn.endheaders() conn.send(b) - response = conn.response_class(conn.sock, method="PUT") + response = conn.response_class(conn.sock, method='PUT') response.begin() self.assertEqual(response.status, 200) self.body = response.read() @@ -758,8 +758,8 @@ class RequestObjectTests(helper.CPWebCase): # Request a PUT method with no body whatsoever (not an empty one). # See https://github.com/cherrypy/cherrypy/issues/650. # Provide a C-T or webtest will provide one (and a C-L) for us. - h = [("Content-Type", "text/plain")] - self.getPage("/method/reachable", headers=h, method="PUT") + h = [('Content-Type', 'text/plain')] + self.getPage('/method/reachable', headers=h, method='PUT') self.assertStatus(411) # Request a custom method with a request body @@ -768,40 +768,40 @@ class RequestObjectTests(helper.CPWebCase): '</prop></propfind>') h = [('Content-Type', 'text/xml'), ('Content-Length', str(len(b)))] - self.getPage("/method/request_body", headers=h, - method="PROPFIND", body=b) + self.getPage('/method/request_body', headers=h, + method='PROPFIND', body=b) self.assertStatus(200) self.assertBody(b) # Request a disallowed method - self.getPage("/method/", method="LINK") + self.getPage('/method/', method='LINK') self.assertStatus(405) # Request an unknown method - self.getPage("/method/", method="SEARCH") + self.getPage('/method/', method='SEARCH') self.assertStatus(501) # For method dispatchers: make sure that an HTTP method doesn't # collide with a virtual path atom. If you build HTTP-method # dispatching into the core, rewrite these handlers to use # your dispatch idioms. - self.getPage("/divorce/get?ID=13") + self.getPage('/divorce/get?ID=13') self.assertBody('Divorce document 13: empty') self.assertStatus(200) - self.getPage("/divorce/", method="GET") + self.getPage('/divorce/', method='GET') self.assertBody('<h1>Choose your document</h1>\n<ul>\n</ul>') self.assertStatus(200) def test_CONNECT_method(self): - if getattr(cherrypy.server, "using_apache", False): - return self.skip("skipped due to known Apache differences... ") + if getattr(cherrypy.server, 'using_apache', False): + return self.skip('skipped due to known Apache differences... ') - self.getPage("/method/", method="CONNECT") - self.assertBody("CONNECT") + self.getPage('/method/', method='CONNECT') + self.assertBody('CONNECT') def testEmptyThreadlocals(self): results = [] for x in range(20): - self.getPage("/threadlocal/") + self.getPage('/threadlocal/') results.append(self.body) - self.assertEqual(results, [ntob("None")] * 20) + self.assertEqual(results, [ntob('None')] * 20) diff --git a/cherrypy/test/test_routes.py b/cherrypy/test/test_routes.py index 6c7ff67e..dc9d009e 100644 --- a/cherrypy/test/test_routes.py +++ b/cherrypy/test/test_routes.py @@ -21,7 +21,7 @@ class RoutesDispatchTest(helper.CPWebCase): class Dummy: def index(self): - return "I said good day!" + return 'I said good day!' class City: @@ -36,11 +36,11 @@ class RoutesDispatchTest(helper.CPWebCase): ], }) def index(self, **kwargs): - return "Welcome to %s, pop. %s" % (self.name, self.population) + return 'Welcome to %s, pop. %s' % (self.name, self.population) def update(self, **kwargs): self.population = kwargs['pop'] - return "OK" + return 'OK' d = cherrypy.dispatch.RoutesDispatcher() d.connect(action='index', name='hounslow', route='/hounslow', @@ -56,21 +56,21 @@ class RoutesDispatchTest(helper.CPWebCase): cherrypy.tree.mount(root=None, config=conf) def test_Routes_Dispatch(self): - self.getPage("/hounslow") - self.assertStatus("200 OK") - self.assertBody("Welcome to Hounslow, pop. 10000") - - self.getPage("/foo") - self.assertStatus("404 Not Found") - - self.getPage("/surbiton") - self.assertStatus("200 OK") - self.assertBody("Welcome to Surbiton, pop. 10000") - - self.getPage("/surbiton", method="POST", body="pop=1327") - self.assertStatus("200 OK") - self.assertBody("OK") - self.getPage("/surbiton") - self.assertStatus("200 OK") - self.assertHeader("Content-Language", "en-GB") - self.assertBody("Welcome to Surbiton, pop. 1327") + self.getPage('/hounslow') + self.assertStatus('200 OK') + self.assertBody('Welcome to Hounslow, pop. 10000') + + self.getPage('/foo') + self.assertStatus('404 Not Found') + + self.getPage('/surbiton') + self.assertStatus('200 OK') + self.assertBody('Welcome to Surbiton, pop. 10000') + + self.getPage('/surbiton', method='POST', body='pop=1327') + self.assertStatus('200 OK') + self.assertBody('OK') + self.getPage('/surbiton') + self.assertStatus('200 OK') + self.assertHeader('Content-Language', 'en-GB') + self.assertBody('Welcome to Surbiton, pop. 1327') diff --git a/cherrypy/test/test_session.py b/cherrypy/test/test_session.py index 5dad9275..391d8370 100755 --- a/cherrypy/test/test_session.py +++ b/cherrypy/test/test_session.py @@ -16,7 +16,7 @@ localDir = os.path.dirname(__file__) def http_methods_allowed(methods=['GET', 'HEAD']): method = cherrypy.request.method.upper() if method not in methods: - cherrypy.response.headers['Allow'] = ", ".join(methods) + cherrypy.response.headers['Allow'] = ', '.join(methods) raise cherrypy.HTTPError(405) cherrypy.tools.allow = cherrypy.Tool('on_start_resource', http_methods_allowed) @@ -60,7 +60,7 @@ def setup_server(): new_cls = reprconf.attributes(new_cls_name) cfg = {'tools.sessions.storage_class': new_cls} self.__class__._cp_config.update(cfg) - if hasattr(cherrypy, "session"): + if hasattr(cherrypy, 'session'): del cherrypy.session if new_cls.clean_thread: new_cls.clean_thread.stop() @@ -83,12 +83,12 @@ def setup_server(): def delete(self): cherrypy.session.delete() sessions.expire() - return "done" + return 'done' @cherrypy.expose def delkey(self, key): del cherrypy.session[key] - return "OK" + return 'OK' @cherrypy.expose def redir_target(self): @@ -109,7 +109,7 @@ def setup_server(): @cherrypy.expose def regen(self): cherrypy.tools.sessions.regenerate() - return "logged in" + return 'logged in' @cherrypy.expose def length(self): @@ -153,7 +153,7 @@ class SessionTest(helper.CPWebCase): self.getPage('/testStr') self.assertBody('1') cookie_parts = dict([p.strip().split('=') - for p in self.cookies[0][1].split(";")]) + for p in self.cookies[0][1].split(';')]) # Assert there is an 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['session_id', 'expires', 'Path'])) @@ -187,7 +187,7 @@ class SessionTest(helper.CPWebCase): # Test session __contains__ self.getPage('/keyin?key=counter', self.cookies) - self.assertBody("True") + self.assertBody('True') cookieset1 = self.cookies # Make a new session and test __len__ again @@ -197,9 +197,9 @@ class SessionTest(helper.CPWebCase): # Test session delete self.getPage('/delete', self.cookies) - self.assertBody("done") + self.assertBody('done') self.getPage('/delete', cookieset1) - self.assertBody("done") + self.assertBody('done') f = lambda: [ x for x in os.listdir(localDir) if x.startswith('session-')] self.assertEqual(f(), []) @@ -225,8 +225,8 @@ class SessionTest(helper.CPWebCase): request_count = 30 # Get initial cookie - self.getPage("/") - self.assertBody("1") + self.getPage('/') + self.assertBody('1') cookies = self.cookies data_dict = {} @@ -274,14 +274,14 @@ class SessionTest(helper.CPWebCase): # Start a new session self.getPage('/testStr') self.getPage('/iredir', self.cookies) - self.assertBody("FileSession") + self.assertBody('FileSession') def test_4_File_deletion(self): # Start a new session self.getPage('/testStr') # Delete the session file manually and retry. - id = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1] - path = os.path.join(localDir, "session-" + id) + id = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1] + path = os.path.join(localDir, 'session-' + id) os.unlink(path) self.getPage('/testStr', self.cookies) @@ -300,21 +300,21 @@ class SessionTest(helper.CPWebCase): def test_6_regenerate(self): self.getPage('/testStr') # grab the cookie ID - id1 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1] + id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1] self.getPage('/regen') self.assertBody('logged in') - id2 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1] + id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1] self.assertNotEqual(id1, id2) self.getPage('/testStr') # grab the cookie ID - id1 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1] + id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1] self.getPage('/testStr', headers=[ ('Cookie', 'session_id=maliciousid; ' 'expires=Sat, 27 Oct 2017 04:18:28 GMT; Path=/;')]) - id2 = self.cookies[0][1].split(";", 1)[0].split("=", 1)[1] + id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1] self.assertNotEqual(id1, id2) self.assertNotEqual(id2, 'maliciousid') @@ -324,7 +324,7 @@ class SessionTest(helper.CPWebCase): self.getPage('/session_cookie') # grab the cookie ID cookie_parts = dict([p.strip().split('=') - for p in self.cookies[0][1].split(";")]) + for p in self.cookies[0][1].split(';')]) # Assert there is no 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path'])) id1 = cookie_parts['temp'] @@ -333,7 +333,7 @@ class SessionTest(helper.CPWebCase): # Send another request in the same "browser session". self.getPage('/session_cookie', self.cookies) cookie_parts = dict([p.strip().split('=') - for p in self.cookies[0][1].split(";")]) + for p in self.cookies[0][1].split(';')]) # Assert there is no 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path'])) self.assertBody(id1) @@ -343,7 +343,7 @@ class SessionTest(helper.CPWebCase): self.getPage('/session_cookie') # grab the cookie ID cookie_parts = dict([p.strip().split('=') - for p in self.cookies[0][1].split(";")]) + for p in self.cookies[0][1].split(';')]) # Assert there is no 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path'])) # Assert a new id has been generated... @@ -357,9 +357,9 @@ class SessionTest(helper.CPWebCase): cache = copykeys(sessions.RamSession.cache) if cache: if cache == [id2]: - self.fail("The second session did not time out.") + self.fail('The second session did not time out.') else: - self.fail("Unknown session id in cache: %r", cache) + self.fail('Unknown session id in cache: %r', cache) def test_8_Ram_Cleanup(self): def lock(): @@ -401,7 +401,7 @@ except (ImportError, socket.error): setup_server = staticmethod(setup_server) def test(self): - return self.skip("memcached not reachable ") + return self.skip('memcached not reachable ') else: class MemcachedSessionTest(helper.CPWebCase): setup_server = staticmethod(setup_server) @@ -417,7 +417,7 @@ else: self.assertBody('3') self.getPage('/length', self.cookies) self.assertErrorPage(500) - self.assertInBody("NotImplementedError") + self.assertInBody('NotImplementedError') self.getPage('/delkey?key=counter', self.cookies) self.assertStatus(200) @@ -428,26 +428,26 @@ else: # Test session __contains__ self.getPage('/keyin?key=counter', self.cookies) - self.assertBody("True") + self.assertBody('True') # Test session delete self.getPage('/delete', self.cookies) - self.assertBody("done") + self.assertBody('done') def test_1_Concurrency(self): client_thread_count = 5 request_count = 30 # Get initial cookie - self.getPage("/") - self.assertBody("1") + self.getPage('/') + self.assertBody('1') cookies = self.cookies data_dict = {} def request(index): for i in range(request_count): - self.getPage("/", cookies) + self.getPage('/', cookies) # Uncomment the following line to prove threads overlap. ## sys.stdout.write("%d " % index) if not self.body.isdigit(): @@ -474,7 +474,7 @@ else: # Start a new session self.getPage('/testStr') self.getPage('/iredir', self.cookies) - self.assertBody("memcached") + self.assertBody('memcached') def test_5_Error_paths(self): self.getPage('/unknown/page') diff --git a/cherrypy/test/test_sessionauthenticate.py b/cherrypy/test/test_sessionauthenticate.py index 8988e985..63053fcb 100644 --- a/cherrypy/test/test_sessionauthenticate.py +++ b/cherrypy/test/test_sessionauthenticate.py @@ -16,7 +16,7 @@ class SessionAuthenticateTest(helper.CPWebCase): # A simple tool to add some things to request.params # This is to check to make sure that session_auth can handle # request params (ticket #780) - cherrypy.request.params["test"] = "test" + cherrypy.request.params['test'] = 'test' cherrypy.tools.augment_params = cherrypy.Tool( 'before_handler', augment_params, None, priority=30) @@ -32,7 +32,7 @@ class SessionAuthenticateTest(helper.CPWebCase): @cherrypy.expose def index(self, **kwargs): - return "Hi %s, you are logged in" % cherrypy.request.login + return 'Hi %s, you are logged in' % cherrypy.request.login cherrypy.tree.mount(Test()) diff --git a/cherrypy/test/test_states.py b/cherrypy/test/test_states.py index 412b52f3..ce6830a8 100644 --- a/cherrypy/test/test_states.py +++ b/cherrypy/test/test_states.py @@ -55,7 +55,7 @@ def setup_server(): @cherrypy.expose def index(self): - return "Hello World" + return 'Hello World' @cherrypy.expose def ctrlc(self): @@ -64,20 +64,20 @@ def setup_server(): @cherrypy.expose def graceful(self): engine.graceful() - return "app was (gracefully) restarted succesfully" + return 'app was (gracefully) restarted succesfully' @cherrypy.expose def block_explicit(self): while True: if cherrypy.response.timed_out: cherrypy.response.timed_out = False - return "broken!" + return 'broken!' time.sleep(0.01) @cherrypy.expose def block_implicit(self): time.sleep(0.5) - return "response.timeout = %s" % cherrypy.response.timeout + return 'response.timeout = %s' % cherrypy.response.timeout cherrypy.tree.mount(Root()) cherrypy.config.update({ @@ -117,8 +117,8 @@ class ServerStateTests(helper.CPWebCase): self.assertEqual(db_connection.startcount, 2) self.assertEqual(len(db_connection.threads), 0) - self.getPage("/") - self.assertBody("Hello World") + self.getPage('/') + self.assertBody('Hello World') self.assertEqual(len(db_connection.threads), 1) # Test engine stop. This will also stop the HTTP server. @@ -131,8 +131,8 @@ class ServerStateTests(helper.CPWebCase): # Block the main thread now and verify that exit() works. def exittest(): - self.getPage("/") - self.assertBody("Hello World") + self.getPage('/') + self.assertBody('Hello World') engine.exit() cherrypy.server.start() engine.start_with_callback(exittest) @@ -147,23 +147,23 @@ class ServerStateTests(helper.CPWebCase): self.assertEqual(db_connection.running, True) grace = db_connection.gracecount - self.getPage("/") - self.assertBody("Hello World") + self.getPage('/') + self.assertBody('Hello World') self.assertEqual(len(db_connection.threads), 1) # Test server restart from this thread engine.graceful() self.assertEqual(engine.state, engine.states.STARTED) - self.getPage("/") - self.assertBody("Hello World") + self.getPage('/') + self.assertBody('Hello World') self.assertEqual(db_connection.running, True) self.assertEqual(db_connection.gracecount, grace + 1) self.assertEqual(len(db_connection.threads), 1) # Test server restart from inside a page handler - self.getPage("/graceful") + self.getPage('/graceful') self.assertEqual(engine.state, engine.states.STARTED) - self.assertBody("app was (gracefully) restarted succesfully") + self.assertBody('app was (gracefully) restarted succesfully') self.assertEqual(db_connection.running, True) self.assertEqual(db_connection.gracecount, grace + 2) # Since we are requesting synchronously, is only one thread used? @@ -184,10 +184,10 @@ class ServerStateTests(helper.CPWebCase): self.persistent = True try: # Make the first request and assert there's no "Connection: close". - self.getPage("/") + self.getPage('/') self.assertStatus('200 OK') - self.assertBody("Hello World") - self.assertNoHeader("Connection") + self.assertBody('Hello World') + self.assertNoHeader('Connection') cherrypy.server.httpserver.interrupt = KeyboardInterrupt engine.block() @@ -222,12 +222,12 @@ class ServerStateTests(helper.CPWebCase): # sideffects. python < 3.5 will raise directly BadStatusLine # which is not a subclass for socket.error/OSError. try: - self.getPage("/ctrlc", raise_subcls=BadStatusLine) + self.getPage('/ctrlc', raise_subcls=BadStatusLine) except BadStatusLine: pass else: print(self.body) - self.fail("AssertionError: BadStatusLine not raised") + self.fail('AssertionError: BadStatusLine not raised') engine.block() self.assertEqual(db_connection.running, False) @@ -243,24 +243,24 @@ class ServerStateTests(helper.CPWebCase): # Request a "normal" page. self.assertEqual(engine.timeout_monitor.servings, []) - self.getPage("/") - self.assertBody("Hello World") + self.getPage('/') + self.assertBody('Hello World') # request.close is called async. while engine.timeout_monitor.servings: - sys.stdout.write(".") + sys.stdout.write('.') time.sleep(0.01) # Request a page that explicitly checks itself for deadlock. # The deadlock_timeout should be 2 secs. - self.getPage("/block_explicit") - self.assertBody("broken!") + self.getPage('/block_explicit') + self.assertBody('broken!') # Request a page that implicitly breaks deadlock. # If we deadlock, we want to touch as little code as possible, # so we won't even call handle_error, just bail ASAP. - self.getPage("/block_implicit") + self.getPage('/block_implicit') self.assertStatus(500) - self.assertInBody("raise cherrypy.TimeoutError()") + self.assertInBody('raise cherrypy.TimeoutError()') finally: engine.exit() @@ -275,14 +275,14 @@ class ServerStateTests(helper.CPWebCase): p.write_conf(extra='test_case_name: "test_4_Autoreload"') p.start(imports='cherrypy.test._test_states_demo') try: - self.getPage("/start") + self.getPage('/start') start = float(self.body) # Give the autoreloader time to cache the file time. time.sleep(2) # Touch the file - os.utime(os.path.join(thisdir, "_test_states_demo.py"), None) + os.utime(os.path.join(thisdir, '_test_states_demo.py'), None) # Give the autoreloader time to re-exec the process time.sleep(2) @@ -290,13 +290,13 @@ class ServerStateTests(helper.CPWebCase): port = cherrypy.server.socket_port cherrypy._cpserver.wait_for_occupied_port(host, port) - self.getPage("/start") + self.getPage('/start') if not (float(self.body) > start): - raise AssertionError("start time %s not greater than %s" % + raise AssertionError('start time %s not greater than %s' % (float(self.body), start)) finally: # Shut down the spawned process - self.getPage("/exit") + self.getPage('/exit') p.join() def test_5_Start_Error(self): @@ -316,14 +316,14 @@ test_case_name: "test_5_Start_Error" ) p.start(imports='cherrypy.test._test_states_demo') if p.exit_code == 0: - self.fail("Process failed to return nonzero exit code.") + self.fail('Process failed to return nonzero exit code.') class PluginTests(helper.CPWebCase): def test_daemonize(self): if os.name not in ['posix']: - return self.skip("skipped (not on posix) ") + return self.skip('skipped (not on posix) ') self.HOST = '127.0.0.1' self.PORT = 8081 # Spawn the process and wait, when this returns, the original process @@ -338,19 +338,19 @@ class PluginTests(helper.CPWebCase): p.start(imports='cherrypy.test._test_states_demo') try: # Just get the pid of the daemonization process. - self.getPage("/pid") + self.getPage('/pid') self.assertStatus(200) page_pid = int(self.body) self.assertEqual(page_pid, p.get_pid()) finally: # Shut down the spawned process - self.getPage("/exit") + self.getPage('/exit') p.join() # Wait until here to test the exit code because we want to ensure # that we wait for the daemon to finish running before we fail. if p.exit_code != 0: - self.fail("Daemonized parent process failed to exit cleanly.") + self.fail('Daemonized parent process failed to exit cleanly.') class SignalHandlingTests(helper.CPWebCase): @@ -360,7 +360,7 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGHUP except ImportError: - return self.skip("skipped (no SIGHUP) ") + return self.skip('skipped (no SIGHUP) ') # Spawn the process. p = helper.CPProcess(ssl=(self.scheme.lower() == 'https')) @@ -377,10 +377,10 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGHUP except ImportError: - return self.skip("skipped (no SIGHUP) ") + return self.skip('skipped (no SIGHUP) ') if os.name not in ['posix']: - return self.skip("skipped (not on posix) ") + return self.skip('skipped (not on posix) ') # Spawn the process and wait, when this returns, the original process # is finished. If it daemonized properly, we should still be able @@ -397,24 +397,24 @@ class SignalHandlingTests(helper.CPWebCase): os.kill(pid, SIGHUP) # Give the server some time to restart time.sleep(2) - self.getPage("/pid") + self.getPage('/pid') self.assertStatus(200) new_pid = int(self.body) self.assertNotEqual(new_pid, pid) finally: # Shut down the spawned process - self.getPage("/exit") + self.getPage('/exit') p.join() def _require_signal_and_kill(self, signal_name): if not hasattr(signal, signal_name): - self.skip("skipped (no %(signal_name)s)" % vars()) + self.skip('skipped (no %(signal_name)s)' % vars()) if not hasattr(os, 'kill'): - self.skip("skipped (no os.kill)") + self.skip('skipped (no os.kill)') def test_SIGTERM(self): - "SIGTERM should shut down the server whether daemonized or not." + 'SIGTERM should shut down the server whether daemonized or not.' self._require_signal_and_kill('SIGTERM') # Spawn a normal, undaemonized process. @@ -447,7 +447,7 @@ class SignalHandlingTests(helper.CPWebCase): # will result in a forced termination of the process. # Therefore, this test is not suitable for Windows. if os.name == 'nt': - self.skip("SIGTERM not available") + self.skip('SIGTERM not available') # Spawn a normal, undaemonized process. p = helper.CPProcess(ssl=(self.scheme.lower() == 'https')) @@ -463,8 +463,8 @@ test_case_name: "test_signal_handler_unsubscribe" # Assert the old handler ran. target_line = open(p.error_log, 'rb').readlines()[-10] - if not ntob("I am an old SIGTERM handler.") in target_line: - self.fail("Old SIGTERM handler did not run.\n%r" % target_line) + if not ntob('I am an old SIGTERM handler.') in target_line: + self.fail('Old SIGTERM handler did not run.\n%r' % target_line) class WaitTests(unittest.TestCase): @@ -519,7 +519,7 @@ class WaitTests(unittest.TestCase): with_shorter_timeouts(do_waiting) def find_free_port(self): - "Find a free port by binding to port 0 then unbinding." + 'Find a free port by binding to port 0 then unbinding.' sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 0)) free_port = sock.getsockname()[1] diff --git a/cherrypy/test/test_static.py b/cherrypy/test/test_static.py index 8e365665..ffc3576d 100644 --- a/cherrypy/test/test_static.py +++ b/cherrypy/test/test_static.py @@ -16,7 +16,7 @@ from cherrypy.test import helper curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) has_space_filepath = os.path.join(curdir, 'static', 'has space.html') -bigfile_filepath = os.path.join(curdir, "static", "bigfile.log") +bigfile_filepath = os.path.join(curdir, 'static', 'bigfile.log') # The file size needs to be big enough such that half the size of it # won't be socket-buffered (or server-buffered) all in one go. See @@ -38,7 +38,7 @@ class StaticTest(helper.CPWebCase): ) if needs_bigfile: with open(bigfile_filepath, 'wb') as f: - f.write(b"x" * BIGFILE_SIZE) + f.write(b'x' * BIGFILE_SIZE) class Root: @@ -72,7 +72,7 @@ class StaticTest(helper.CPWebCase): @cherrypy.expose def dynamic(self): - return "This is a DYNAMIC page" + return 'This is a DYNAMIC page' root = Root() root.static = Static() @@ -131,24 +131,24 @@ class StaticTest(helper.CPWebCase): pass def test_static(self): - self.getPage("/static/index.html") + self.getPage('/static/index.html') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html') self.assertBody('Hello, world\r\n') # Using a staticdir.root value in a subdir... - self.getPage("/docroot/index.html") + self.getPage('/docroot/index.html') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html') self.assertBody('Hello, world\r\n') # Check a filename with spaces in it - self.getPage("/static/has%20space.html") + self.getPage('/static/has%20space.html') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html') self.assertBody('Hello, world\r\n') - self.getPage("/style.css") + self.getPage('/style.css') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/css') # Note: The body should be exactly 'Dummy stylesheet\n', but @@ -159,98 +159,98 @@ class StaticTest(helper.CPWebCase): def test_fallthrough(self): # Test that NotFound will then try dynamic handlers (see [878]). - self.getPage("/static/dynamic") - self.assertBody("This is a DYNAMIC page") + self.getPage('/static/dynamic') + self.assertBody('This is a DYNAMIC page') # Check a directory via fall-through to dynamic handler. - self.getPage("/static/") + self.getPage('/static/') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html;charset=utf-8') self.assertBody('You want the Baron? You can have the Baron!') def test_index(self): # Check a directory via "staticdir.index". - self.getPage("/docroot/") + self.getPage('/docroot/') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/html') self.assertBody('Hello, world\r\n') # The same page should be returned even if redirected. - self.getPage("/docroot") + self.getPage('/docroot') self.assertStatus(301) self.assertHeader('Location', '%s/docroot/' % self.base()) self.assertMatchesBody("This resource .* <a href=(['\"])%s/docroot/\\1>" - "%s/docroot/</a>." % (self.base(), self.base())) + '%s/docroot/</a>.' % (self.base(), self.base())) def test_config_errors(self): # Check that we get an error if no .file or .dir - self.getPage("/error/thing.html") + self.getPage('/error/thing.html') self.assertErrorPage(500) if sys.version_info >= (3, 3): errmsg = ( - "TypeError: staticdir\(\) missing 2 " - "required positional arguments" + 'TypeError: staticdir\(\) missing 2 ' + 'required positional arguments' ) else: errmsg = ( - "TypeError: staticdir\(\) takes at least 2 " - "(positional )?arguments \(0 given\)" + 'TypeError: staticdir\(\) takes at least 2 ' + '(positional )?arguments \(0 given\)' ) self.assertMatchesBody(errmsg.encode('ascii')) def test_security(self): # Test up-level security - self.getPage("/static/../../test/style.css") + self.getPage('/static/../../test/style.css') self.assertStatus((400, 403)) def test_modif(self): # Test modified-since on a reasonably-large file - self.getPage("/static/dirback.jpg") - self.assertStatus("200 OK") - lastmod = "" + self.getPage('/static/dirback.jpg') + self.assertStatus('200 OK') + lastmod = '' for k, v in self.headers: if k == 'Last-Modified': lastmod = v - ims = ("If-Modified-Since", lastmod) - self.getPage("/static/dirback.jpg", headers=[ims]) + ims = ('If-Modified-Since', lastmod) + self.getPage('/static/dirback.jpg', headers=[ims]) self.assertStatus(304) - self.assertNoHeader("Content-Type") - self.assertNoHeader("Content-Length") - self.assertNoHeader("Content-Disposition") - self.assertBody("") + self.assertNoHeader('Content-Type') + self.assertNoHeader('Content-Length') + self.assertNoHeader('Content-Disposition') + self.assertBody('') def test_755_vhost(self): - self.getPage("/test/", [('Host', 'virt.net')]) + self.getPage('/test/', [('Host', 'virt.net')]) self.assertStatus(200) - self.getPage("/test", [('Host', 'virt.net')]) + self.getPage('/test', [('Host', 'virt.net')]) self.assertStatus(301) self.assertHeader('Location', self.scheme + '://virt.net/test/') def test_serve_fileobj(self): - self.getPage("/fileobj") + self.getPage('/fileobj') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/css;charset=utf-8') self.assertMatchesBody('^Dummy stylesheet') def test_serve_bytesio(self): - self.getPage("/bytesio") + self.getPage('/bytesio') self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/plain;charset=utf-8') self.assertHeader('Content-Length', 14) self.assertMatchesBody('Fee\nfie\nfo\nfum') def test_file_stream(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Make an initial request self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/bigfile", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/bigfile', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) @@ -263,12 +263,12 @@ class StaticTest(helper.CPWebCase): body += data remaining -= len(data) - if self.scheme == "https": + if self.scheme == 'https': newconn = HTTPSConnection else: newconn = HTTPConnection s, h, b = helper.webtest.openURL( - b"/tell", headers=[], host=self.HOST, port=self.PORT, + b'/tell', headers=[], host=self.HOST, port=self.PORT, http_conn=newconn) if not b: # The file was closed on the server. @@ -300,39 +300,39 @@ class StaticTest(helper.CPWebCase): if tell_position >= BIGFILE_SIZE: if read_so_far < (BIGFILE_SIZE / 2): self.fail( - "The file should have advanced to position %r, but " - "has already advanced to the end of the file. It " - "may not be streamed as intended, or at the wrong " - "chunk size (64k)" % read_so_far) + 'The file should have advanced to position %r, but ' + 'has already advanced to the end of the file. It ' + 'may not be streamed as intended, or at the wrong ' + 'chunk size (64k)' % read_so_far) elif tell_position < read_so_far: self.fail( - "The file should have advanced to position %r, but has " - "only advanced to position %r. It may not be streamed " - "as intended, or at the wrong chunk size (64k)" % + 'The file should have advanced to position %r, but has ' + 'only advanced to position %r. It may not be streamed ' + 'as intended, or at the wrong chunk size (64k)' % (read_so_far, tell_position)) - if body != b"x" * BIGFILE_SIZE: + if body != b'x' * BIGFILE_SIZE: self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." % (BIGFILE_SIZE, body[:50], len(body))) conn.close() def test_file_stream_deadlock(self): - if cherrypy.server.protocol_version != "HTTP/1.1": + if cherrypy.server.protocol_version != 'HTTP/1.1': return self.skip() - self.PROTOCOL = "HTTP/1.1" + self.PROTOCOL = 'HTTP/1.1' # Make an initial request but abort early. self.persistent = True conn = self.HTTP_CONN - conn.putrequest("GET", "/bigfile", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/bigfile', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() - response = conn.response_class(conn.sock, method="GET") + response = conn.response_class(conn.sock, method='GET') response.begin() self.assertEqual(response.status, 200) body = response.fp.read(65536) - if body != b"x" * len(body): + if body != b'x' * len(body): self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." % (65536, body[:50], len(body))) response.close() @@ -340,27 +340,27 @@ class StaticTest(helper.CPWebCase): # Make a second request, which should fetch the whole file. self.persistent = False - self.getPage("/bigfile") - if self.body != b"x" * BIGFILE_SIZE: + self.getPage('/bigfile') + if self.body != b'x' * BIGFILE_SIZE: self.fail("Body != 'x' * %d. Got %r instead (%d bytes)." % (BIGFILE_SIZE, self.body[:50], len(body))) def test_error_page_with_serve_file(self): - self.getPage("/404test/yunyeen") + self.getPage('/404test/yunyeen') self.assertStatus(404) self.assertInBody("I couldn't find that thing") def test_null_bytes(self): - self.getPage("/static/\x00") + self.getPage('/static/\x00') self.assertStatus('404 Not Found') @staticmethod @contextlib.contextmanager def unicode_file(): - filename = ntou("Слава Україні.html", 'utf-8') - filepath = os.path.join(curdir, "static", filename) + filename = ntou('Слава Україні.html', 'utf-8') + filepath = os.path.join(curdir, 'static', filename) with io.open(filepath, 'w', encoding='utf-8') as strm: - strm.write(ntou("Героям Слава!", 'utf-8')) + strm.write(ntou('Героям Слава!', 'utf-8')) try: yield finally: @@ -368,13 +368,13 @@ class StaticTest(helper.CPWebCase): def test_unicode(self): with self.unicode_file(): - url = ntou("/static/Слава Україні.html", 'utf-8') + url = ntou('/static/Слава Україні.html', 'utf-8') # quote function requires str url = tonative(url, 'utf-8') url = urllib.parse.quote(url) self.getPage(url) - expected = ntou("Героям Слава!", 'utf-8') + expected = ntou('Героям Слава!', 'utf-8') self.assertInBody(expected) diff --git a/cherrypy/test/test_tools.py b/cherrypy/test/test_tools.py index e2f8f9bb..294e2ec4 100644 --- a/cherrypy/test/test_tools.py +++ b/cherrypy/test/test_tools.py @@ -29,10 +29,10 @@ class ToolTests(helper.CPWebCase): def setup_server(): # Put check_access in a custom toolbox with its own namespace - myauthtools = cherrypy._cptools.Toolbox("myauth") + myauthtools = cherrypy._cptools.Toolbox('myauth') def check_access(default=False): - if not getattr(cherrypy.request, "userid", default): + if not getattr(cherrypy.request, 'userid', default): raise cherrypy.HTTPError(401) myauthtools.check_access = cherrypy.Tool( 'before_request_body', check_access) @@ -49,7 +49,7 @@ class ToolTests(helper.CPWebCase): def _setup(self): def makemap(): - m = self._merged_args().get("map", {}) + m = self._merged_args().get('map', {}) cherrypy.request.numerify_map = copyitems(m) cherrypy.request.hooks.attach('on_start_resource', makemap) @@ -68,21 +68,21 @@ class ToolTests(helper.CPWebCase): def __init__(self): self.ended = {} - self._name = "nadsat" + self._name = 'nadsat' def nadsat(self): def nadsat_it_up(body): for chunk in body: - chunk = chunk.replace(ntob("good"), ntob("horrorshow")) - chunk = chunk.replace(ntob("piece"), ntob("lomtick")) + chunk = chunk.replace(ntob('good'), ntob('horrorshow')) + chunk = chunk.replace(ntob('piece'), ntob('lomtick')) yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) nadsat.priority = 0 def cleanup(self): # This runs after the request has been completely written out. - cherrypy.response.body = [ntob("razdrez")] - id = cherrypy.request.params.get("id") + cherrypy.response.body = [ntob('razdrez')] + id = cherrypy.request.params.get('id') if id: self.ended[id] = True cleanup.failsafe = True @@ -126,7 +126,7 @@ class ToolTests(helper.CPWebCase): @cherrypy.expose def index(self): - return "Howdy earth!" + return 'Howdy earth!' @cherrypy.expose @cherrypy.config(**{'tools.streamer.on': True, 'tools.streamer.arg': 'arg value'}) @@ -143,8 +143,8 @@ class ToolTests(helper.CPWebCase): assert cbnames == ['gzip'], cbnames priorities = [x.priority for x in hooks] assert priorities == [80], priorities - yield ntou("Hello,") - yield ntou("world") + yield ntou('Hello,') + yield ntou('world') yield europoundUnicode # Bare hooks @@ -157,8 +157,8 @@ class ToolTests(helper.CPWebCase): # Note that rotator must run before gzip. @cherrypy.expose def decorated_euro(self, *vpath): - yield ntou("Hello,") - yield ntou("world") + yield ntou('Hello,') + yield ntou('world') yield europoundUnicode decorated_euro = tools.gzip(compress_level=6)(decorated_euro) decorated_euro = tools.rotator(scale=3)(decorated_euro) @@ -180,11 +180,11 @@ class ToolTests(helper.CPWebCase): # METHOD ONE: # Declare Tools in _cp_config - @cherrypy.config(**{"tools.nadsat.on": True}) + @cherrypy.config(**{'tools.nadsat.on': True}) class Demo(Test): def index(self, id=None): - return "A good piece of cherry pie" + return 'A good piece of cherry pie' def ended(self, id): return repr(tools.nadsat.ended[id]) @@ -193,21 +193,21 @@ class ToolTests(helper.CPWebCase): raise ValueError() def errinstream(self, id=None): - yield "nonconfidential" + yield 'nonconfidential' raise ValueError() - yield "confidential" + yield 'confidential' # METHOD TWO: decorator using Tool() # We support Python 2.3, but the @-deco syntax would look like # this: # @tools.check_access() def restricted(self): - return "Welcome!" + return 'Welcome!' restricted = myauthtools.check_access()(restricted) userid = restricted def err_in_onstart(self): - return "success!" + return 'success!' @cherrypy.config(**{'response.stream': True}) def stream(self, id=None): @@ -219,7 +219,7 @@ class ToolTests(helper.CPWebCase): # Declare Tools in detached config '/demo': { 'tools.numerify.on': True, - 'tools.numerify.map': {ntob("pie"): ntob("3.14159")}, + 'tools.numerify.map': {ntob('pie'): ntob('3.14159')}, }, '/demo/restricted': { 'request.show_tracebacks': False, @@ -233,7 +233,7 @@ class ToolTests(helper.CPWebCase): }, '/demo/err_in_onstart': { # Because this isn't a dict, on_start_resource will error. - 'tools.numerify.map': "pie->3.14159" + 'tools.numerify.map': 'pie->3.14159' }, # Combined tools '/euro': { @@ -253,49 +253,49 @@ class ToolTests(helper.CPWebCase): root.tooldecs = _test_decorators.ToolExamples() def testHookErrors(self): - self.getPage("/demo/?id=1") + self.getPage('/demo/?id=1') # If body is "razdrez", then on_end_request is being called too early. - self.assertBody("A horrorshow lomtick of cherry 3.14159") + self.assertBody('A horrorshow lomtick of cherry 3.14159') # If this fails, then on_end_request isn't being called at all. time.sleep(0.1) - self.getPage("/demo/ended/1") - self.assertBody("True") + self.getPage('/demo/ended/1') + self.assertBody('True') valerr = '\n raise ValueError()\nValueError' - self.getPage("/demo/err?id=3") + self.getPage('/demo/err?id=3') # If body is "razdrez", then on_end_request is being called too early. self.assertErrorPage(502, pattern=valerr) # If this fails, then on_end_request isn't being called at all. time.sleep(0.1) - self.getPage("/demo/ended/3") - self.assertBody("True") + self.getPage('/demo/ended/3') + self.assertBody('True') # If body is "razdrez", then on_end_request is being called too early. - if (cherrypy.server.protocol_version == "HTTP/1.0" or - getattr(cherrypy.server, "using_apache", False)): - self.getPage("/demo/errinstream?id=5") + if (cherrypy.server.protocol_version == 'HTTP/1.0' or + getattr(cherrypy.server, 'using_apache', False)): + self.getPage('/demo/errinstream?id=5') # Because this error is raised after the response body has # started, the status should not change to an error status. - self.assertStatus("200 OK") - self.assertBody("nonconfidential") + self.assertStatus('200 OK') + self.assertBody('nonconfidential') else: # Because this error is raised after the response body has # started, and because it's chunked output, an error is raised by # the HTTP client when it encounters incomplete output. self.assertRaises((ValueError, IncompleteRead), self.getPage, - "/demo/errinstream?id=5") + '/demo/errinstream?id=5') # If this fails, then on_end_request isn't being called at all. time.sleep(0.1) - self.getPage("/demo/ended/5") - self.assertBody("True") + self.getPage('/demo/ended/5') + self.assertBody('True') # Test the "__call__" technique (compile-time decorator). - self.getPage("/demo/restricted") + self.getPage('/demo/restricted') self.assertErrorPage(401) # Test compile-time decorator with kwargs from config. - self.getPage("/demo/userid") - self.assertBody("Welcome!") + self.getPage('/demo/userid') + self.assertBody('Welcome!') def testEndRequestOnDrop(self): old_timeout = None @@ -312,8 +312,8 @@ class ToolTests(helper.CPWebCase): self.persistent = True try: conn = self.HTTP_CONN - conn.putrequest("GET", "/demo/stream?id=9", skip_host=True) - conn.putheader("Host", self.HOST) + conn.putrequest('GET', '/demo/stream?id=9', skip_host=True) + conn.putheader('Host', self.HOST) conn.endheaders() # Skip the rest of the request and close the conn. This will # cause the server's active socket to error, which *should* @@ -324,8 +324,8 @@ class ToolTests(helper.CPWebCase): self.persistent = False time.sleep(timeout * 2) # Test that the on_end_request hook was called. - self.getPage("/demo/ended/9") - self.assertBody("True") + self.getPage('/demo/ended/9') + self.assertBody('True') finally: if old_timeout is not None: httpserver.timeout = old_timeout @@ -336,23 +336,23 @@ class ToolTests(helper.CPWebCase): # This is NOT true of the other hooks. # Here, we have set up a failure in NumerifyTool.numerify_map, # but our 'critical' hook should run and set the error to 502. - self.getPage("/demo/err_in_onstart") + self.getPage('/demo/err_in_onstart') self.assertErrorPage(502) self.assertInBody( "AttributeError: 'str' object has no attribute 'items'") def testCombinedTools(self): - expectedResult = (ntou("Hello,world") + + expectedResult = (ntou('Hello,world') + europoundUnicode).encode('utf-8') zbuf = io.BytesIO() zfile = gzip.GzipFile(mode='wb', fileobj=zbuf, compresslevel=9) zfile.write(expectedResult) zfile.close() - self.getPage("/euro", + self.getPage('/euro', headers=[ - ("Accept-Encoding", "gzip"), - ("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")]) + ('Accept-Encoding', 'gzip'), + ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')]) self.assertInBody(zbuf.getvalue()[:3]) zbuf = io.BytesIO() @@ -360,15 +360,15 @@ class ToolTests(helper.CPWebCase): zfile.write(expectedResult) zfile.close() - self.getPage("/decorated_euro", headers=[("Accept-Encoding", "gzip")]) + self.getPage('/decorated_euro', headers=[('Accept-Encoding', 'gzip')]) self.assertInBody(zbuf.getvalue()[:3]) # This returns a different value because gzip's priority was # lowered in conf, allowing the rotator to run after gzip. # Of course, we don't want breakage in production apps, # but it proves the priority was changed. - self.getPage("/decorated_euro/subpath", - headers=[("Accept-Encoding", "gzip")]) + self.getPage('/decorated_euro/subpath', + headers=[('Accept-Encoding', 'gzip')]) if six.PY3: self.assertInBody(bytes([(x + 3) % 256 for x in zbuf.getvalue()])) else: @@ -376,20 +376,20 @@ class ToolTests(helper.CPWebCase): for x in zbuf.getvalue()])) def testBareHooks(self): - content = "bit of a pain in me gulliver" - self.getPage("/pipe", - headers=[("Content-Length", str(len(content))), - ("Content-Type", "text/plain")], - method="POST", body=content) + content = 'bit of a pain in me gulliver' + self.getPage('/pipe', + headers=[('Content-Length', str(len(content))), + ('Content-Type', 'text/plain')], + method='POST', body=content) self.assertBody(content) def testHandlerWrapperTool(self): - self.getPage("/tarfile") - self.assertBody("I am a tarfile") + self.getPage('/tarfile') + self.assertBody('I am a tarfile') def testToolWithConfig(self): if not sys.version_info >= (2, 5): - return self.skip("skipped (Python 2.5+ only)") + return self.skip('skipped (Python 2.5+ only)') self.getPage('/tooldecs/blah') self.assertHeader('Content-Type', 'application/data') @@ -401,7 +401,7 @@ class ToolTests(helper.CPWebCase): except AttributeError: pass else: - raise AssertionError("Tool.on did not error as it should have.") + raise AssertionError('Tool.on did not error as it should have.') # set try: @@ -409,7 +409,7 @@ class ToolTests(helper.CPWebCase): except AttributeError: pass else: - raise AssertionError("Tool.on did not error as it should have.") + raise AssertionError('Tool.on did not error as it should have.') def testDecorator(self): @cherrypy.tools.register('on_start_resource') diff --git a/cherrypy/test/test_tutorials.py b/cherrypy/test/test_tutorials.py index bfcd50f7..e3a47b13 100644 --- a/cherrypy/test/test_tutorials.py +++ b/cherrypy/test/test_tutorials.py @@ -30,7 +30,7 @@ class TutorialTest(helper.CPWebCase): """ Import or reload tutorial module as needed. """ - target = "cherrypy.tutorial." + name + target = 'cherrypy.tutorial.' + name if target in sys.modules: module = imp.reload(sys.modules[target]) elif 'importlib' not in globals(): @@ -55,32 +55,32 @@ class TutorialTest(helper.CPWebCase): def test01HelloWorld(self): self.setup_tutorial('tut01_helloworld', 'HelloWorld') - self.getPage("/") + self.getPage('/') self.assertBody('Hello world!') def test02ExposeMethods(self): self.setup_tutorial('tut02_expose_methods', 'HelloWorld') - self.getPage("/show_msg") + self.getPage('/show_msg') self.assertBody('Hello world!') def test03GetAndPost(self): self.setup_tutorial('tut03_get_and_post', 'WelcomePage') # Try different GET queries - self.getPage("/greetUser?name=Bob") + self.getPage('/greetUser?name=Bob') self.assertBody("Hey Bob, what's up?") - self.getPage("/greetUser") + self.getPage('/greetUser') self.assertBody('Please enter your name <a href="./">here</a>.') - self.getPage("/greetUser?name=") + self.getPage('/greetUser?name=') self.assertBody('No, really, enter your name <a href="./">here</a>.') # Try the same with POST - self.getPage("/greetUser", method="POST", body="name=Bob") + self.getPage('/greetUser', method='POST', body='name=Bob') self.assertBody("Hey Bob, what's up?") - self.getPage("/greetUser", method="POST", body="name=") + self.getPage('/greetUser', method='POST', body='name=') self.assertBody('No, really, enter your name <a href="./">here</a>.') def test04ComplexSite(self): @@ -95,7 +95,7 @@ class TutorialTest(helper.CPWebCase): </ul> <p>[<a href="../">Return to links page</a>]</p>''' - self.getPage("/links/extra/") + self.getPage('/links/extra/') self.assertBody(msg) def test05DerivedObjects(self): @@ -118,32 +118,32 @@ class TutorialTest(helper.CPWebCase): # the tutorial has some annoying spaces in otherwise blank lines msg = msg.replace('</h2>\n\n', '</h2>\n \n') msg = msg.replace('</p>\n\n', '</p>\n \n') - self.getPage("/another/") + self.getPage('/another/') self.assertBody(msg) def test06DefaultMethod(self): - self.setup_tutorial("tut06_default_method", "UsersPage") + self.setup_tutorial('tut06_default_method', 'UsersPage') self.getPage('/hendrik') self.assertBody('Hendrik Mans, CherryPy co-developer & crazy German ' '(<a href="./">back</a>)') def test07Sessions(self): - self.setup_tutorial("tut07_sessions", "HitCounter") + self.setup_tutorial('tut07_sessions', 'HitCounter') self.getPage('/') self.assertBody( "\n During your current session, you've viewed this" - "\n page 1 times! Your life is a patio of fun!" - "\n ") + '\n page 1 times! Your life is a patio of fun!' + '\n ') self.getPage('/', self.cookies) self.assertBody( "\n During your current session, you've viewed this" - "\n page 2 times! Your life is a patio of fun!" - "\n ") + '\n page 2 times! Your life is a patio of fun!' + '\n ') def test08GeneratorsAndYield(self): - self.setup_tutorial("tut08_generators_and_yield", "GeneratorDemo") + self.setup_tutorial('tut08_generators_and_yield', 'GeneratorDemo') self.getPage('/') self.assertBody('<html><body><h2>Generators rule!</h2>' '<h3>List of users:</h3>' @@ -151,19 +151,19 @@ class TutorialTest(helper.CPWebCase): '</body></html>') def test09Files(self): - self.setup_tutorial("tut09_files", "FileDemo") + self.setup_tutorial('tut09_files', 'FileDemo') # Test upload filesize = 5 - h = [("Content-type", "multipart/form-data; boundary=x"), - ("Content-Length", str(105 + filesize))] + h = [('Content-type', 'multipart/form-data; boundary=x'), + ('Content-Length', str(105 + filesize))] b = ('--x\n' 'Content-Disposition: form-data; name="myFile"; ' 'filename="hello.txt"\r\n' 'Content-Type: text/plain\r\n' '\r\n') b += 'a' * filesize + '\n' + '--x--\n' - self.getPage('/upload', h, "POST", b) + self.getPage('/upload', h, 'POST', b) self.assertBody('''<html> <body> myFile length: %d<br /> @@ -174,44 +174,44 @@ class TutorialTest(helper.CPWebCase): # Test download self.getPage('/download') - self.assertStatus("200 OK") - self.assertHeader("Content-Type", "application/x-download") - self.assertHeader("Content-Disposition", + self.assertStatus('200 OK') + self.assertHeader('Content-Type', 'application/x-download') + self.assertHeader('Content-Disposition', # Make sure the filename is quoted. 'attachment; filename="pdf_file.pdf"') self.assertEqual(len(self.body), 85698) def test10HTTPErrors(self): - self.setup_tutorial("tut10_http_errors", "HTTPErrorDemo") + self.setup_tutorial('tut10_http_errors', 'HTTPErrorDemo') @cherrypy.expose def traceback_setting(): return repr(cherrypy.request.show_tracebacks) cherrypy.tree.mount(traceback_setting, '/traceback_setting') - self.getPage("/") + self.getPage('/') self.assertInBody("""<a href="toggleTracebacks">""") self.assertInBody("""<a href="/doesNotExist">""") self.assertInBody("""<a href="/error?code=403">""") self.assertInBody("""<a href="/error?code=500">""") self.assertInBody("""<a href="/messageArg">""") - self.getPage("/traceback_setting") + self.getPage('/traceback_setting') setting = self.body - self.getPage("/toggleTracebacks") + self.getPage('/toggleTracebacks') self.assertStatus((302, 303)) - self.getPage("/traceback_setting") + self.getPage('/traceback_setting') self.assertBody(str(not eval(setting))) - self.getPage("/error?code=500") + self.getPage('/error?code=500') self.assertStatus(500) - self.assertInBody("The server encountered an unexpected condition " - "which prevented it from fulfilling the request.") + self.assertInBody('The server encountered an unexpected condition ' + 'which prevented it from fulfilling the request.') - self.getPage("/error?code=403") + self.getPage('/error?code=403') self.assertStatus(403) self.assertInBody("<h2>You can't do that!</h2>") - self.getPage("/messageArg") + self.getPage('/messageArg') self.assertStatus(500) self.assertInBody("If you construct an HTTPError with a 'message'") diff --git a/cherrypy/test/test_virtualhost.py b/cherrypy/test/test_virtualhost.py index d0af0fd6..de88f927 100644 --- a/cherrypy/test/test_virtualhost.py +++ b/cherrypy/test/test_virtualhost.py @@ -14,15 +14,15 @@ class VirtualHostTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "Hello, world" + return 'Hello, world' @cherrypy.expose def dom4(self): - return "Under construction" + return 'Under construction' @cherrypy.expose def method(self, value): - return "You sent %s" % value + return 'You sent %s' % value class VHost: @@ -31,23 +31,23 @@ class VirtualHostTest(helper.CPWebCase): @cherrypy.expose def index(self): - return "Welcome to %s" % self.sitename + return 'Welcome to %s' % self.sitename @cherrypy.expose def vmethod(self, value): - return "You sent %s" % value + return 'You sent %s' % value @cherrypy.expose def url(self): - return cherrypy.url("nextpage") + return cherrypy.url('nextpage') # Test static as a handler (section must NOT include vhost prefix) static = cherrypy.tools.staticdir.handler( section='/static', dir=curdir) root = Root() - root.mydom2 = VHost("Domain 2") - root.mydom3 = VHost("Domain 3") + root.mydom2 = VHost('Domain 2') + root.mydom3 = VHost('Domain 3') hostmap = {'www.mydom2.com': '/mydom2', 'www.mydom3.com': '/mydom3', 'www.mydom4.com': '/dom4', @@ -66,48 +66,48 @@ class VirtualHostTest(helper.CPWebCase): }) def testVirtualHost(self): - self.getPage("/", [('Host', 'www.mydom1.com')]) + self.getPage('/', [('Host', 'www.mydom1.com')]) self.assertBody('Hello, world') - self.getPage("/mydom2/", [('Host', 'www.mydom1.com')]) + self.getPage('/mydom2/', [('Host', 'www.mydom1.com')]) self.assertBody('Welcome to Domain 2') - self.getPage("/", [('Host', 'www.mydom2.com')]) + self.getPage('/', [('Host', 'www.mydom2.com')]) self.assertBody('Welcome to Domain 2') - self.getPage("/", [('Host', 'www.mydom3.com')]) + self.getPage('/', [('Host', 'www.mydom3.com')]) self.assertBody('Welcome to Domain 3') - self.getPage("/", [('Host', 'www.mydom4.com')]) + self.getPage('/', [('Host', 'www.mydom4.com')]) self.assertBody('Under construction') # Test GET, POST, and positional params - self.getPage("/method?value=root") - self.assertBody("You sent root") - self.getPage("/vmethod?value=dom2+GET", [('Host', 'www.mydom2.com')]) - self.assertBody("You sent dom2 GET") - self.getPage("/vmethod", [('Host', 'www.mydom3.com')], method="POST", - body="value=dom3+POST") - self.assertBody("You sent dom3 POST") - self.getPage("/vmethod/pos", [('Host', 'www.mydom3.com')]) - self.assertBody("You sent pos") + self.getPage('/method?value=root') + self.assertBody('You sent root') + self.getPage('/vmethod?value=dom2+GET', [('Host', 'www.mydom2.com')]) + self.assertBody('You sent dom2 GET') + self.getPage('/vmethod', [('Host', 'www.mydom3.com')], method='POST', + body='value=dom3+POST') + self.assertBody('You sent dom3 POST') + self.getPage('/vmethod/pos', [('Host', 'www.mydom3.com')]) + self.assertBody('You sent pos') # Test that cherrypy.url uses the browser url, not the virtual url - self.getPage("/url", [('Host', 'www.mydom2.com')]) - self.assertBody("%s://www.mydom2.com/nextpage" % self.scheme) + self.getPage('/url', [('Host', 'www.mydom2.com')]) + self.assertBody('%s://www.mydom2.com/nextpage' % self.scheme) def test_VHost_plus_Static(self): # Test static as a handler - self.getPage("/static/style.css", [('Host', 'www.mydom2.com')]) + self.getPage('/static/style.css', [('Host', 'www.mydom2.com')]) self.assertStatus('200 OK') self.assertHeader('Content-Type', 'text/css;charset=utf-8') # Test static in config - self.getPage("/static2/dirback.jpg", [('Host', 'www.mydom2.com')]) + self.getPage('/static2/dirback.jpg', [('Host', 'www.mydom2.com')]) self.assertStatus('200 OK') self.assertHeaderIn('Content-Type', ['image/jpeg', 'image/pjpeg']) # Test static config with "index" arg - self.getPage("/static2/", [('Host', 'www.mydom2.com')]) + self.getPage('/static2/', [('Host', 'www.mydom2.com')]) self.assertStatus('200 OK') self.assertBody('Hello, world\r\n') # Since tools.trailing_slash is on by default, this should redirect - self.getPage("/static2", [('Host', 'www.mydom2.com')]) + self.getPage('/static2', [('Host', 'www.mydom2.com')]) self.assertStatus(301) diff --git a/cherrypy/test/test_wsgi_ns.py b/cherrypy/test/test_wsgi_ns.py index 2d333e03..2a5fedd4 100644 --- a/cherrypy/test/test_wsgi_ns.py +++ b/cherrypy/test/test_wsgi_ns.py @@ -24,7 +24,7 @@ class WSGI_Namespace_Test(helper.CPWebCase): return next(self.iter) def close(self): - if hasattr(self.appresults, "close"): + if hasattr(self.appresults, 'close'): self.appresults.close() class ChangeCase(object): @@ -73,7 +73,7 @@ class WSGI_Namespace_Test(helper.CPWebCase): @cherrypy.expose def index(self): - return "HellO WoRlD!" + return 'HellO WoRlD!' root_conf = {'wsgi.pipeline': [('replace', Replacer)], 'wsgi.replace.map': {ntob('L'): ntob('X'), @@ -89,6 +89,6 @@ class WSGI_Namespace_Test(helper.CPWebCase): if not cherrypy.server.httpserver: return self.skip() - self.getPage("/") + self.getPage('/') # If body is "HEXXO WORXD!", the middleware was applied out of order. - self.assertBody("HERRO WORRD!") + self.assertBody('HERRO WORRD!') diff --git a/cherrypy/test/test_wsgi_unix_socket.py b/cherrypy/test/test_wsgi_unix_socket.py index 7a829d51..57d7a541 100644 --- a/cherrypy/test/test_wsgi_unix_socket.py +++ b/cherrypy/test/test_wsgi_unix_socket.py @@ -47,8 +47,8 @@ def skip_on_windows(method): Decorator to skip the method call if the test is executing on Windows. """ def wrapper(self): - if sys.platform == "win32": - return self.skip("No UNIX Socket support in Windows.") + if sys.platform == 'win32': + return self.skip('No UNIX Socket support in Windows.') else: return method(self) wrapper.__doc__ = method.__doc__ @@ -73,11 +73,11 @@ class WSGI_UnixSocket_Test(helper.CPWebCase): @cherrypy.expose def index(self): - return "Test OK" + return 'Test OK' @cherrypy.expose def error(self): - raise Exception("Invalid page") + raise Exception('Invalid page') config = { 'server.socket_file': USOCKET_PATH @@ -90,17 +90,17 @@ class WSGI_UnixSocket_Test(helper.CPWebCase): @skip_on_windows def test_simple_request(self): - self.getPage("/") - self.assertStatus("200 OK") - self.assertInBody("Test OK") + self.getPage('/') + self.assertStatus('200 OK') + self.assertInBody('Test OK') @skip_on_windows def test_not_found(self): - self.getPage("/invalid_path") - self.assertStatus("404 Not Found") + self.getPage('/invalid_path') + self.assertStatus('404 Not Found') @skip_on_windows def test_internal_error(self): - self.getPage("/error") - self.assertStatus("500 Internal Server Error") - self.assertInBody("Invalid page") + self.getPage('/error') + self.assertStatus('500 Internal Server Error') + self.assertInBody('Invalid page') diff --git a/cherrypy/test/test_wsgi_vhost.py b/cherrypy/test/test_wsgi_vhost.py index 2c9ddfc2..2b6e5ba9 100644 --- a/cherrypy/test/test_wsgi_vhost.py +++ b/cherrypy/test/test_wsgi_vhost.py @@ -14,7 +14,7 @@ class WSGI_VirtualHost_Test(helper.CPWebCase): @cherrypy.expose def index(self): - return "Welcome to the %s website!" % self.name + return 'Welcome to the %s website!' % self.name default = cherrypy.Application(None) @@ -27,9 +27,9 @@ class WSGI_VirtualHost_Test(helper.CPWebCase): def test_welcome(self): if not cherrypy.server.using_wsgi: - return self.skip("skipped (not using WSGI)... ") + return self.skip('skipped (not using WSGI)... ') for year in range(1997, 2008): self.getPage( - "/", headers=[('Host', 'www.classof%s.example' % year)]) - self.assertBody("Welcome to the Class of %s website!" % year) + '/', headers=[('Host', 'www.classof%s.example' % year)]) + self.assertBody('Welcome to the Class of %s website!' % year) diff --git a/cherrypy/test/test_wsgiapps.py b/cherrypy/test/test_wsgiapps.py index 104d2b66..2ae3ab15 100644 --- a/cherrypy/test/test_wsgiapps.py +++ b/cherrypy/test/test_wsgiapps.py @@ -50,7 +50,7 @@ class WSGIGraftTests(helper.CPWebCase): return self.iter.next() def close(self): - if hasattr(self.appresults, "close"): + if hasattr(self.appresults, 'close'): self.appresults.close() class ReversingMiddleware(object): @@ -72,7 +72,7 @@ class WSGIGraftTests(helper.CPWebCase): def next(this): line = list(this.iter.next()) line.reverse() - return "".join(line) + return ''.join(line) return Reverser(results) @@ -96,31 +96,31 @@ class WSGIGraftTests(helper.CPWebCase): This is a wsgi app running within CherryPy!''' def test_01_standard_app(self): - self.getPage("/") + self.getPage('/') self.assertBody("I'm a regular CherryPy page handler!") def test_04_pure_wsgi(self): import cherrypy if not cherrypy.server.using_wsgi: - return self.skip("skipped (not using WSGI)... ") - self.getPage("/hosted/app1") - self.assertHeader("Content-Type", "text/plain") + return self.skip('skipped (not using WSGI)... ') + self.getPage('/hosted/app1') + self.assertHeader('Content-Type', 'text/plain') self.assertInBody(self.wsgi_output) def test_05_wrapped_cp_app(self): import cherrypy if not cherrypy.server.using_wsgi: - return self.skip("skipped (not using WSGI)... ") - self.getPage("/hosted/app2/") + return self.skip('skipped (not using WSGI)... ') + self.getPage('/hosted/app2/') body = list("I'm a regular CherryPy page handler!") body.reverse() - body = "".join(body) + body = ''.join(body) self.assertInBody(body) def test_06_empty_string_app(self): import cherrypy if not cherrypy.server.using_wsgi: - return self.skip("skipped (not using WSGI)... ") - self.getPage("/hosted/app3") - self.assertHeader("Content-Type", "text/plain") + return self.skip('skipped (not using WSGI)... ') + self.getPage('/hosted/app3') + self.assertHeader('Content-Type', 'text/plain') self.assertInBody('Hello world') diff --git a/cherrypy/test/test_xmlrpc.py b/cherrypy/test/test_xmlrpc.py index 254730b7..14376b92 100644 --- a/cherrypy/test/test_xmlrpc.py +++ b/cherrypy/test/test_xmlrpc.py @@ -18,7 +18,7 @@ if six.PY3: # Python 3.0's SafeTransport still mistakenly checks for socket.ssl import socket - if not hasattr(socket, "ssl"): + if not hasattr(socket, 'ssl'): socket.ssl = True else: class HTTPSTransport(SafeTransport): @@ -65,7 +65,7 @@ def setup_server(): @cherrypy.expose def foo(self): - return "Hello world!" + return 'Hello world!' @cherrypy.expose def return_single_item_list(self): @@ -73,7 +73,7 @@ def setup_server(): @cherrypy.expose def return_string(self): - return "here is a string" + return 'here is a string' @cherrypy.expose def return_tuple(self): @@ -109,7 +109,7 @@ def setup_server(): @cherrypy.expose def test_returning_Fault(self): - return Fault(1, "custom Fault response") + return Fault(1, 'custom Fault response') root = Root() root.xmlrpc = XmlRpc() @@ -125,7 +125,7 @@ class XmlRpcTest(helper.CPWebCase): def testXmlRpc(self): scheme = self.scheme - if scheme == "https": + if scheme == 'https': url = 'https://%s:%s/xmlrpc/' % (self.interface(), self.PORT) proxy = ServerProxy(url, transport=HTTPSTransport()) else: @@ -133,12 +133,12 @@ class XmlRpcTest(helper.CPWebCase): proxy = ServerProxy(url) # begin the tests ... - self.getPage("/xmlrpc/foo") - self.assertBody("Hello world!") + self.getPage('/xmlrpc/foo') + self.assertBody('Hello world!') self.assertEqual(proxy.return_single_item_list(), [42]) self.assertNotEqual(proxy.return_single_item_list(), 'one bazillion') - self.assertEqual(proxy.return_string(), "here is a string") + self.assertEqual(proxy.return_string(), 'here is a string') self.assertEqual(proxy.return_tuple(), list(('here', 'is', 1, 'tuple'))) self.assertEqual(proxy.return_dict(), {'a': 1, 'c': 3, 'b': 2}) @@ -157,10 +157,10 @@ class XmlRpcTest(helper.CPWebCase): except Exception: x = sys.exc_info()[1] self.assertEqual(x.__class__, Fault) - self.assertEqual(x.faultString, ("unsupported operand type(s) " + self.assertEqual(x.faultString, ('unsupported operand type(s) ' "for *: 'dict' and 'int'")) else: - self.fail("Expected xmlrpclib.Fault") + self.fail('Expected xmlrpclib.Fault') # https://github.com/cherrypy/cherrypy/issues/533 # if a method is not found, an xmlrpclib.Fault should be raised @@ -172,7 +172,7 @@ class XmlRpcTest(helper.CPWebCase): self.assertEqual(x.faultString, 'method "non_method" is not supported') else: - self.fail("Expected xmlrpclib.Fault") + self.fail('Expected xmlrpclib.Fault') # Test returning a Fault from the page handler. try: @@ -180,6 +180,6 @@ class XmlRpcTest(helper.CPWebCase): except Exception: x = sys.exc_info()[1] self.assertEqual(x.__class__, Fault) - self.assertEqual(x.faultString, ("custom Fault response")) + self.assertEqual(x.faultString, ('custom Fault response')) else: - self.fail("Expected xmlrpclib.Fault") + self.fail('Expected xmlrpclib.Fault') diff --git a/cherrypy/test/webtest.py b/cherrypy/test/webtest.py index 8e8352be..d7447d13 100644 --- a/cherrypy/test/webtest.py +++ b/cherrypy/test/webtest.py @@ -41,10 +41,10 @@ def interface(host): or '::' (IN6ADDR_ANY), this will return the proper localhost.""" if host == '0.0.0.0': # INADDR_ANY, which should respond on localhost. - return "127.0.0.1" + return '127.0.0.1' if host == '::': # IN6ADDR_ANY, which should respond on localhost. - return "::1" + return '::1' return host @@ -67,21 +67,21 @@ class TerseTestRunner(unittest.TextTestRunner): return TerseTestResult(self.stream, self.descriptions, self.verbosity) def run(self, test): - "Run the given test case or test suite." + 'Run the given test case or test suite.' # Overridden to remove unnecessary empty lines and separators result = self._makeResult() test(result) result.printErrors() if not result.wasSuccessful(): - self.stream.write("FAILED (") + self.stream.write('FAILED (') failed, errored = list(map(len, (result.failures, result.errors))) if failed: - self.stream.write("failures=%d" % failed) + self.stream.write('failures=%d' % failed) if errored: if failed: - self.stream.write(", ") - self.stream.write("errors=%d" % errored) - self.stream.writeln(")") + self.stream.write(', ') + self.stream.write('errors=%d' % errored) + self.stream.writeln(')') return result @@ -100,11 +100,11 @@ class ReloadingTestLoader(unittest.TestLoader): unused_parts = [] if module is None: if not parts: - raise ValueError("incomplete test name: %s" % name) + raise ValueError('incomplete test name: %s' % name) else: parts_copy = parts[:] while parts_copy: - target = ".".join(parts_copy) + target = '.'.join(parts_copy) if target in sys.modules: module = reload(sys.modules[target]) parts = unused_parts @@ -139,11 +139,11 @@ class ReloadingTestLoader(unittest.TestLoader): test = obj() if not isinstance(test, unittest.TestCase) and \ not isinstance(test, unittest.TestSuite): - raise ValueError("calling %s returned %s, " - "not a test" % (obj, test)) + raise ValueError('calling %s returned %s, ' + 'not a test' % (obj, test)) return test else: - raise ValueError("do not know how to make test from: %s" % obj) + raise ValueError('do not know how to make test from: %s' % obj) try: @@ -177,8 +177,8 @@ except ImportError: # from jaraco.properties class NonDataProperty(object): def __init__(self, fget): - assert fget is not None, "fget cannot be none" - assert callable(fget), "fget must be callable" + assert fget is not None, 'fget cannot be none' + assert callable(fget), 'fget must be callable' self.fget = fget def __get__(self, obj, objtype=None): @@ -188,12 +188,12 @@ class NonDataProperty(object): class WebCase(unittest.TestCase): - HOST = "127.0.0.1" + HOST = '127.0.0.1' PORT = 8000 HTTP_CONN = HTTPConnection - PROTOCOL = "HTTP/1.1" + PROTOCOL = 'HTTP/1.1' - scheme = "http" + scheme = 'http' url = None status = None @@ -206,7 +206,7 @@ class WebCase(unittest.TestCase): def get_conn(self, auto_open=False): """Return a connection to our HTTP server.""" - if self.scheme == "https": + if self.scheme == 'https': cls = HTTPSConnection else: cls = HTTPConnection @@ -234,13 +234,13 @@ class WebCase(unittest.TestCase): if on: self.HTTP_CONN = self.get_conn(auto_open=auto_open) else: - if self.scheme == "https": + if self.scheme == 'https': self.HTTP_CONN = HTTPSConnection else: self.HTTP_CONN = HTTPConnection def _get_persistent(self): - return hasattr(self.HTTP_CONN, "__class__") + return hasattr(self.HTTP_CONN, '__class__') def _set_persistent(self, on): self.set_persistent(on) @@ -253,7 +253,7 @@ class WebCase(unittest.TestCase): or '::' (IN6ADDR_ANY), this will return the proper localhost.""" return interface(self.HOST) - def getPage(self, url, headers=None, method="GET", body=None, + def getPage(self, url, headers=None, method='GET', body=None, protocol=None, raise_subcls=None): """Open the url with debugging support. Return status, headers, body. @@ -299,47 +299,47 @@ class WebCase(unittest.TestCase): console_height = 30 def _handlewebError(self, msg): - print("") - print(" ERROR: %s" % msg) + print('') + print(' ERROR: %s' % msg) if not self.interactive: raise self.failureException(msg) - p = (" Show: " - "[B]ody [H]eaders [S]tatus [U]RL; " - "[I]gnore, [R]aise, or sys.e[X]it >> ") + p = (' Show: ' + '[B]ody [H]eaders [S]tatus [U]RL; ' + '[I]gnore, [R]aise, or sys.e[X]it >> ') sys.stdout.write(p) sys.stdout.flush() while True: i = getchar().upper() - if not isinstance(i, type("")): + if not isinstance(i, type('')): i = i.decode('ascii') - if i not in "BHSUIRX": + if i not in 'BHSUIRX': continue print(i.upper()) # Also prints new line - if i == "B": + if i == 'B': for x, line in enumerate(self.body.splitlines()): if (x + 1) % self.console_height == 0: # The \r and comma should make the next line overwrite - sys.stdout.write("<-- More -->\r") + sys.stdout.write('<-- More -->\r') m = getchar().lower() # Erase our "More" prompt - sys.stdout.write(" \r") - if m == "q": + sys.stdout.write(' \r') + if m == 'q': break print(line) - elif i == "H": + elif i == 'H': pprint.pprint(self.headers) - elif i == "S": + elif i == 'S': print(self.status) - elif i == "U": + elif i == 'U': print(self.url) - elif i == "I": + elif i == 'I': # return without raising the normal exception return - elif i == "R": + elif i == 'R': raise self.failureException(msg) - elif i == "X": + elif i == 'X': self.exit() sys.stdout.write(p) sys.stdout.flush() @@ -412,7 +412,7 @@ class WebCase(unittest.TestCase): return value if msg is None: - msg = "%r not in %r" % (value, header_values) + msg = '%r not in %r' % (value, header_values) self._handlewebError(msg) def assertNoHeader(self, key, msg=None): @@ -462,7 +462,7 @@ class WebCase(unittest.TestCase): self._handlewebError(msg) -methods_with_bodies = ("POST", "PUT") +methods_with_bodies = ('POST', 'PUT') def cleanHeaders(headers, method, body, host, port): @@ -479,9 +479,9 @@ def cleanHeaders(headers, method, body, host, port): break if not found: if port == 80: - headers.append(("Host", host)) + headers.append(('Host', host)) else: - headers.append(("Host", "%s:%s" % (host, port))) + headers.append(('Host', '%s:%s' % (host, port))) if method in methods_with_bodies: # Stick in default type and length headers if not present @@ -492,8 +492,8 @@ def cleanHeaders(headers, method, body, host, port): break if not found: headers.append( - ("Content-Type", "application/x-www-form-urlencoded")) - headers.append(("Content-Length", str(len(body or "")))) + ('Content-Type', 'application/x-www-form-urlencoded')) + headers.append(('Content-Length', str(len(body or '')))) return headers @@ -507,23 +507,23 @@ def shb(response): key, value = None, None for line in response.msg.headers: if line: - if line[0] in " \t": + if line[0] in ' \t': value += line.strip() else: if key and value: h.append((key, value)) - key, value = line.split(":", 1) + 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() + return '%s %s' % (response.status, response.reason), h, response.read() -def openURL(url, headers=None, method="GET", body=None, - host="127.0.0.1", port=8000, http_conn=HTTPConnection, - protocol="HTTP/1.1", raise_subcls=None): +def openURL(url, headers=None, method='GET', body=None, + host='127.0.0.1', port=8000, http_conn=HTTPConnection, + protocol='HTTP/1.1', raise_subcls=None): """ Open the given HTTP resource and return status, headers, and body. @@ -539,13 +539,13 @@ def openURL(url, headers=None, method="GET", body=None, for trial in range(10): try: # Allow http_conn to be a class or an instance - if hasattr(http_conn, "host"): + if hasattr(http_conn, 'host'): conn = http_conn else: conn = http_conn(interface(host), port) conn._http_vsn_str = protocol - conn._http_vsn = int("".join([x for x in protocol if x.isdigit()])) + conn._http_vsn = int(''.join([x for x in protocol if x.isdigit()])) if six.PY3 and isinstance(url, bytes): url = url.decode() @@ -553,7 +553,7 @@ def openURL(url, headers=None, method="GET", body=None, skip_accept_encoding=True) for key, value in headers: - conn.putheader(key, value.encode("Latin-1")) + conn.putheader(key, value.encode('Latin-1')) conn.endheaders() if body is not None: @@ -564,7 +564,7 @@ def openURL(url, headers=None, method="GET", body=None, s, h, b = shb(response) - if not hasattr(http_conn, "host"): + if not hasattr(http_conn, 'host'): # We made our own conn instance. Close it. conn.close() @@ -607,6 +607,6 @@ def server_error(exc=None): return False else: ServerError.on = True - print("") - print("".join(traceback.format_exception(*exc))) + print('') + print(''.join(traceback.format_exception(*exc))) return True diff --git a/cherrypy/tutorial/tut01_helloworld.py b/cherrypy/tutorial/tut01_helloworld.py index 9ee427b3..e86793c8 100644 --- a/cherrypy/tutorial/tut01_helloworld.py +++ b/cherrypy/tutorial/tut01_helloworld.py @@ -22,7 +22,7 @@ class HelloWorld: # its return value to the client. Because this is tutorial # lesson number 01, we'll just send something really simple. # How about... - return "Hello world!" + return 'Hello world!' tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') diff --git a/cherrypy/tutorial/tut02_expose_methods.py b/cherrypy/tutorial/tut02_expose_methods.py index 2b4a8649..882a2c45 100644 --- a/cherrypy/tutorial/tut02_expose_methods.py +++ b/cherrypy/tutorial/tut02_expose_methods.py @@ -20,7 +20,7 @@ class HelloWorld: @cherrypy.expose def show_msg(self): # Here's the important message! - return "Hello world!" + return 'Hello world!' tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') diff --git a/cherrypy/tutorial/tut06_default_method.py b/cherrypy/tutorial/tut06_default_method.py index 8188d84c..0ce4cabe 100644 --- a/cherrypy/tutorial/tut06_default_method.py +++ b/cherrypy/tutorial/tut06_default_method.py @@ -41,13 +41,13 @@ class UsersPage: # application, we would probably do some database lookups here # instead of the silly if/elif/else construct. if user == 'remi': - out = "Remi Delon, CherryPy lead developer" + out = 'Remi Delon, CherryPy lead developer' elif user == 'hendrik': - out = "Hendrik Mans, CherryPy co-developer & crazy German" + out = 'Hendrik Mans, CherryPy co-developer & crazy German' elif user == 'lorenzo': - out = "Lorenzo Lamas, famous actor and singer!" + out = 'Lorenzo Lamas, famous actor and singer!' else: - out = "Unknown user. :-(" + out = 'Unknown user. :-(' return '%s (<a href="./">back</a>)' % out diff --git a/cherrypy/tutorial/tut08_generators_and_yield.py b/cherrypy/tutorial/tut08_generators_and_yield.py index 709051dd..18f42f93 100644 --- a/cherrypy/tutorial/tut08_generators_and_yield.py +++ b/cherrypy/tutorial/tut08_generators_and_yield.py @@ -15,10 +15,10 @@ import cherrypy class GeneratorDemo: def header(self): - return "<html><body><h2>Generators rule!</h2>" + return '<html><body><h2>Generators rule!</h2>' def footer(self): - return "</body></html>" + return '</body></html>' @cherrypy.expose def index(self): @@ -27,10 +27,10 @@ class GeneratorDemo: # Every yield line adds one part to the total result body. yield self.header() - yield "<h3>List of users:</h3>" + yield '<h3>List of users:</h3>' for user in users: - yield "%s<br/>" % user + yield '%s<br/>' % user yield self.footer() diff --git a/cherrypy/tutorial/tut09_files.py b/cherrypy/tutorial/tut09_files.py index 0694f614..48585cbe 100644 --- a/cherrypy/tutorial/tut09_files.py +++ b/cherrypy/tutorial/tut09_files.py @@ -91,9 +91,9 @@ class FileDemo(object): @cherrypy.expose def download(self): - path = os.path.join(absDir, "pdf_file.pdf") - return static.serve_file(path, "application/x-download", - "attachment", os.path.basename(path)) + path = os.path.join(absDir, 'pdf_file.pdf') + return static.serve_file(path, 'application/x-download', + 'attachment', os.path.basename(path)) tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') diff --git a/cherrypy/tutorial/tut10_http_errors.py b/cherrypy/tutorial/tut10_http_errors.py index fcc6d733..18f02fd0 100644 --- a/cherrypy/tutorial/tut10_http_errors.py +++ b/cherrypy/tutorial/tut10_http_errors.py @@ -21,7 +21,7 @@ class HTTPErrorDemo(object): # Set a custom response for 403 errors. _cp_config = {'error_page.403': - os.path.join(curpath, "custom_error.html")} + os.path.join(curpath, 'custom_error.html')} @cherrypy.expose def index(self): @@ -70,8 +70,8 @@ class HTTPErrorDemo(object): @cherrypy.expose def messageArg(self): message = ("If you construct an HTTPError with a 'message' " - "argument, it wil be placed on the error page " - "(underneath the status line by default).") + 'argument, it wil be placed on the error page ' + '(underneath the status line by default).') raise cherrypy.HTTPError(500, message=message) diff --git a/cherrypy/wsgiserver/__init__.py b/cherrypy/wsgiserver/__init__.py index 18b58322..4af58523 100644 --- a/cherrypy/wsgiserver/__init__.py +++ b/cherrypy/wsgiserver/__init__.py @@ -115,7 +115,7 @@ __all__ = ['HTTPRequest', 'HTTPConnection', 'HTTPServer', 'socket_errors_to_ignore'] -if 'win' in sys.platform and hasattr(socket, "AF_INET6"): +if 'win' in sys.platform and hasattr(socket, 'AF_INET6'): if not hasattr(socket, 'IPPROTO_IPV6'): socket.IPPROTO_IPV6 = 41 if not hasattr(socket, 'IPV6_V6ONLY'): @@ -166,7 +166,7 @@ NUMBER_SIGN = ntob('#') QUESTION_MARK = ntob('?') ASTERISK = ntob('*') FORWARD_SLASH = ntob('/') -quoted_slash = re.compile(ntob("(?i)%2F")) +quoted_slash = re.compile(ntob('(?i)%2F')) def plat_specific_errors(*errnames): @@ -181,23 +181,23 @@ def plat_specific_errors(*errnames): # de-dupe the list return list(dict.fromkeys(nums).keys()) -socket_error_eintr = plat_specific_errors("EINTR", "WSAEINTR") +socket_error_eintr = plat_specific_errors('EINTR', 'WSAEINTR') socket_errors_to_ignore = plat_specific_errors( - "EPIPE", - "EBADF", "WSAEBADF", - "ENOTSOCK", "WSAENOTSOCK", - "ETIMEDOUT", "WSAETIMEDOUT", - "ECONNREFUSED", "WSAECONNREFUSED", - "ECONNRESET", "WSAECONNRESET", - "ECONNABORTED", "WSAECONNABORTED", - "ENETRESET", "WSAENETRESET", - "EHOSTDOWN", "EHOSTUNREACH", + 'EPIPE', + 'EBADF', 'WSAEBADF', + 'ENOTSOCK', 'WSAENOTSOCK', + 'ETIMEDOUT', 'WSAETIMEDOUT', + 'ECONNREFUSED', 'WSAECONNREFUSED', + 'ECONNRESET', 'WSAECONNRESET', + 'ECONNABORTED', 'WSAECONNABORTED', + 'ENETRESET', 'WSAENETRESET', + 'EHOSTDOWN', 'EHOSTUNREACH', ) -socket_errors_to_ignore.append("timed out") -socket_errors_to_ignore.append("The read operation timed out") +socket_errors_to_ignore.append('timed out') +socket_errors_to_ignore.append('The read operation timed out') if sys.platform == 'darwin': - socket_errors_to_ignore.append(plat_specific_errors("EPROTOTYPE")) + socket_errors_to_ignore.append(plat_specific_errors('EPROTOTYPE')) socket_errors_nonblocking = plat_specific_errors( 'EAGAIN', 'EWOULDBLOCK', 'WSAEWOULDBLOCK') @@ -236,13 +236,13 @@ def read_headers(rfile, hdict=None): line = rfile.readline() if not line: # No more data--illegal end of headers - raise ValueError("Illegal end of headers.") + raise ValueError('Illegal end of headers.') if line == CRLF: # Normal end of headers break if not line.endswith(CRLF): - raise ValueError("HTTP requires CRLF terminators") + raise ValueError('HTTP requires CRLF terminators') if line[0] in (SPACE, TAB): # It's a continuation line. @@ -251,7 +251,7 @@ def read_headers(rfile, hdict=None): try: k, v = line.split(COLON, 1) except ValueError: - raise ValueError("Illegal header line.") + raise ValueError('Illegal header line.') # TODO: what about TE and WWW-Authenticate? k = k.strip().title() v = v.strip() @@ -260,7 +260,7 @@ def read_headers(rfile, hdict=None): if k in comma_separated_headers: existing = hdict.get(hname) if existing: - v = b", ".join((existing, v)) + v = b', '.join((existing, v)) hdict[hname] = v return hdict @@ -422,7 +422,7 @@ class ChunkedRFile(object): self.bytes_read += len(line) if self.maxlen and self.bytes_read > self.maxlen: - raise MaxSizeExceeded("Request Entity Too Large", self.maxlen) + raise MaxSizeExceeded('Request Entity Too Large', self.maxlen) line = line.strip().split(SEMICOLON, 1) @@ -430,7 +430,7 @@ class ChunkedRFile(object): chunk_size = line.pop(0) chunk_size = int(chunk_size, 16) except ValueError: - raise ValueError("Bad chunked transfer size: " + repr(chunk_size)) + raise ValueError('Bad chunked transfer size: ' + repr(chunk_size)) if chunk_size <= 0: self.closed = True @@ -439,7 +439,7 @@ class ChunkedRFile(object): ## if line: chunk_extension = line[0] if self.maxlen and self.bytes_read + chunk_size > self.maxlen: - raise IOError("Request Entity Too Large") + raise IOError('Request Entity Too Large') chunk = self.rfile.read(chunk_size) self.bytes_read += len(chunk) @@ -449,7 +449,7 @@ class ChunkedRFile(object): if crlf != CRLF: raise ValueError( "Bad chunked transfer coding (expected '\\r\\n', " - "got " + repr(crlf) + ")") + 'got ' + repr(crlf) + ')') def read(self, size=None): data = EMPTY @@ -515,23 +515,23 @@ class ChunkedRFile(object): def read_trailer_lines(self): if not self.closed: raise ValueError( - "Cannot read trailers until the request body has been read.") + 'Cannot read trailers until the request body has been read.') while True: line = self.rfile.readline() if not line: # No more data--illegal end of headers - raise ValueError("Illegal end of headers.") + raise ValueError('Illegal end of headers.') self.bytes_read += len(line) if self.maxlen and self.bytes_read > self.maxlen: - raise IOError("Request Entity Too Large") + raise IOError('Request Entity Too Large') if line == CRLF: # Normal end of headers break if not line.endswith(CRLF): - raise ValueError("HTTP requires CRLF terminators") + raise ValueError('HTTP requires CRLF terminators') yield line @@ -579,14 +579,14 @@ class HTTPRequest(object): self.ready = False self.started_request = False - self.scheme = ntob("http") + self.scheme = ntob('http') if self.server.ssl_adapter is not None: - self.scheme = ntob("https") + self.scheme = ntob('https') # Use the lowest-common protocol in case read_request_line errors. self.response_protocol = 'HTTP/1.0' self.inheaders = {} - self.status = "" + self.status = '' self.outheaders = [] self.sent_headers = False self.close_connection = self.__class__.close_connection @@ -601,9 +601,9 @@ class HTTPRequest(object): success = self.read_request_line() except MaxSizeExceeded: self.simple_response( - "414 Request-URI Too Long", - "The Request-URI sent with the request exceeds the maximum " - "allowed bytes.") + '414 Request-URI Too Long', + 'The Request-URI sent with the request exceeds the maximum ' + 'allowed bytes.') return else: if not success: @@ -613,9 +613,9 @@ class HTTPRequest(object): success = self.read_request_headers() except MaxSizeExceeded: self.simple_response( - "413 Request Entity Too Large", - "The headers sent with the request exceed the maximum " - "allowed bytes.") + '413 Request Entity Too Large', + 'The headers sent with the request exceed the maximum ' + 'allowed bytes.') return else: if not success: @@ -650,7 +650,7 @@ class HTTPRequest(object): if not request_line.endswith(CRLF): self.simple_response( - "400 Bad Request", "HTTP requires CRLF terminators") + '400 Bad Request', 'HTTP requires CRLF terminators') return False try: @@ -658,7 +658,7 @@ class HTTPRequest(object): req_protocol_str = req_protocol.decode('ascii') rp = int(req_protocol_str[5]), int(req_protocol_str[7]) except (ValueError, IndexError): - self.simple_response("400 Bad Request", "Malformed Request-Line") + self.simple_response('400 Bad Request', 'Malformed Request-Line') return False self.uri = uri @@ -667,12 +667,12 @@ class HTTPRequest(object): # uri may be an abs_path (including "http://host.domain.tld"); scheme, authority, path = self.parse_request_uri(uri) if path is None: - self.simple_response("400 Bad Request", - "Invalid path in Request-URI.") + self.simple_response('400 Bad Request', + 'Invalid path in Request-URI.') return False if NUMBER_SIGN in path: - self.simple_response("400 Bad Request", - "Illegal #fragment in Request-URI.") + self.simple_response('400 Bad Request', + 'Illegal #fragment in Request-URI.') return False if scheme: @@ -693,9 +693,9 @@ class HTTPRequest(object): atoms = [unquote_to_bytes(x) for x in quoted_slash.split(path)] except ValueError: ex = sys.exc_info()[1] - self.simple_response("400 Bad Request", ex.args[0]) + self.simple_response('400 Bad Request', ex.args[0]) return False - path = b"%2F".join(atoms) + path = b'%2F'.join(atoms) self.path = path # Note that, like wsgiref and most other HTTP servers, @@ -717,11 +717,11 @@ class HTTPRequest(object): sp = int(self.server.protocol[5]), int(self.server.protocol[7]) if sp[0] != rp[0]: - self.simple_response("505 HTTP Version Not Supported") + self.simple_response('505 HTTP Version Not Supported') return False self.request_protocol = req_protocol - self.response_protocol = "HTTP/%s.%s" % min(rp, sp) + self.response_protocol = 'HTTP/%s.%s' % min(rp, sp) return True @@ -733,44 +733,44 @@ class HTTPRequest(object): read_headers(self.rfile, self.inheaders) except ValueError: ex = sys.exc_info()[1] - self.simple_response("400 Bad Request", ex.args[0]) + self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size - if mrbs and int(self.inheaders.get(b"Content-Length", 0)) > mrbs: + if mrbs and int(self.inheaders.get(b'Content-Length', 0)) > mrbs: self.simple_response( - "413 Request Entity Too Large", - "The entity sent with the request exceeds the maximum " - "allowed bytes.") + '413 Request Entity Too Large', + 'The entity sent with the request exceeds the maximum ' + 'allowed bytes.') return False # Persistent connection support - if self.response_protocol == "HTTP/1.1": + if self.response_protocol == 'HTTP/1.1': # Both server and client are HTTP/1.1 - if self.inheaders.get(b"Connection", b"") == b"close": + if self.inheaders.get(b'Connection', b'') == b'close': self.close_connection = True else: # Either the server or client (or both) are HTTP/1.0 - if self.inheaders.get(b"Connection", b"") != b"Keep-Alive": + if self.inheaders.get(b'Connection', b'') != b'Keep-Alive': self.close_connection = True # Transfer-Encoding support te = None - if self.response_protocol == "HTTP/1.1": - te = self.inheaders.get(b"Transfer-Encoding") + if self.response_protocol == 'HTTP/1.1': + te = self.inheaders.get(b'Transfer-Encoding') if te: - te = [x.strip().lower() for x in te.split(b",") if x.strip()] + te = [x.strip().lower() for x in te.split(b',') if x.strip()] self.chunked_read = False if te: for enc in te: - if enc == b"chunked": + if enc == b'chunked': self.chunked_read = True else: # Note that, even if we see "chunked", we must reject # if there is an extension we don't recognize. - self.simple_response("501 Unimplemented") + self.simple_response('501 Unimplemented') self.close_connection = True return False @@ -791,12 +791,12 @@ class HTTPRequest(object): # # We used to do 3, but are now doing 1. Maybe we'll do 2 someday, # but it seems like it would be a big slowdown for such a rare case. - if self.inheaders.get(b"Expect", b"") == b"100-continue": + if self.inheaders.get(b'Expect', b'') == b'100-continue': # Don't use simple_response here, because it emits headers # we don't want. See # https://github.com/cherrypy/cherrypy/issues/951 msg = self.server.protocol.encode('ascii') - msg += b" 100 Continue\r\n\r\n" + msg += b' 100 Continue\r\n\r\n' try: self.conn.wfile.write(msg) except socket.error: @@ -849,13 +849,13 @@ class HTTPRequest(object): if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: - cl = int(self.inheaders.get(b"Content-Length", 0)) + cl = int(self.inheaders.get(b'Content-Length', 0)) if mrbs and mrbs < cl: if not self.sent_headers: self.simple_response( - "413 Request Entity Too Large", - "The entity sent with the request exceeds the " - "maximum allowed bytes.") + '413 Request Entity Too Large', + 'The entity sent with the request exceeds the ' + 'maximum allowed bytes.') return self.rfile = KnownLengthRFile(self.conn.rfile, cl) @@ -865,37 +865,37 @@ class HTTPRequest(object): self.sent_headers = True self.send_headers() if self.chunked_write: - self.conn.wfile.write(b"0\r\n\r\n") + self.conn.wfile.write(b'0\r\n\r\n') - def simple_response(self, status, msg=""): + def simple_response(self, status, msg=''): """Write a simple response back to the client.""" status = str(status) - proto_status = "%s %s\r\n" % (self.server.protocol, status) - content_length = "Content-Length: %s\r\n" % len(msg) - content_type = "Content-Type: text/plain\r\n" + proto_status = '%s %s\r\n' % (self.server.protocol, status) + content_length = 'Content-Length: %s\r\n' % len(msg) + content_type = 'Content-Type: text/plain\r\n' buf = [ - proto_status.encode("ISO-8859-1"), - content_length.encode("ISO-8859-1"), - content_type.encode("ISO-8859-1"), + proto_status.encode('ISO-8859-1'), + content_length.encode('ISO-8859-1'), + content_type.encode('ISO-8859-1'), ] - if status[:3] in ("413", "414"): + if status[:3] in ('413', '414'): # Request Entity Too Large / Request-URI Too Long self.close_connection = True if self.response_protocol == 'HTTP/1.1': # This will not be true for 414, since read_request_line # usually raises 414 before reading the whole line, and we # therefore cannot know the proper response_protocol. - buf.append(b"Connection: close\r\n") + buf.append(b'Connection: close\r\n') else: # HTTP/1.0 had no 413/414 status nor Connection header. # Emit 400 instead and trust the message body is enough. - status = "400 Bad Request" + status = '400 Bad Request' buf.append(CRLF) if msg: if isinstance(msg, six.text_type): - msg = msg.encode("ISO-8859-1") + msg = msg.encode('ISO-8859-1') buf.append(msg) try: @@ -925,7 +925,7 @@ class HTTPRequest(object): if status == 413: # Request Entity Too Large. Close conn to avoid garbage. self.close_connection = True - elif b"content-length" not in hkeys: + elif b'content-length' not in hkeys: # "All 1xx (informational), 204 (no content), # and 304 (not modified) responses MUST NOT # include a message-body." So no point chunking. @@ -936,20 +936,20 @@ class HTTPRequest(object): and self.method != b'HEAD'): # Use the chunked transfer-coding self.chunked_write = True - self.outheaders.append((b"Transfer-Encoding", b"chunked")) + self.outheaders.append((b'Transfer-Encoding', b'chunked')) else: # Closing the conn is the only way to determine len. self.close_connection = True - if b"connection" not in hkeys: + if b'connection' not in hkeys: if self.response_protocol == 'HTTP/1.1': # Both server and client are HTTP/1.1 or better if self.close_connection: - self.outheaders.append((b"Connection", b"close")) + self.outheaders.append((b'Connection', b'close')) else: # Server and/or client are HTTP/1.0 if not self.close_connection: - self.outheaders.append((b"Connection", b"Keep-Alive")) + self.outheaders.append((b'Connection', b'Keep-Alive')) if (not self.close_connection) and (not self.chunked_read): # Read any remaining request body data on the socket. @@ -968,15 +968,15 @@ class HTTPRequest(object): if remaining > 0: self.rfile.read(remaining) - if b"date" not in hkeys: + if b'date' not in hkeys: self.outheaders.append(( - b"Date", + b'Date', email.utils.formatdate(usegmt=True).encode('ISO-8859-1'), )) - if b"server" not in hkeys: + if b'server' not in hkeys: self.outheaders.append(( - b"Server", + b'Server', self.server.server_name.encode('ISO-8859-1'), )) @@ -1015,7 +1015,7 @@ class CP_BufferedWriter(io.BufferedWriter): return len(b) def _flush_unlocked(self): - self._checkClosed("flush of closed file") + self._checkClosed('flush of closed file') while self._write_buf: try: # ssl sockets only except 'bytes', not bytearrays @@ -1059,7 +1059,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): def flush(self): if self._wbuf: - buffer = "".join(self._wbuf) + buffer = ''.join(self._wbuf) self._wbuf = [] self.write(buffer) @@ -1146,7 +1146,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buf.write(data) del data # explicit free break - assert n <= left, "recv(%d) returned %d bytes" % (left, n) + assert n <= left, 'recv(%d) returned %d bytes' % (left, n) buf.write(data) buf_len += n del data # explicit free @@ -1175,12 +1175,12 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): self._rbuf = io.BytesIO() data = None recv = self.recv - while data != "\n": + while data != '\n': data = recv(1) if not data: break buffers.append(data) - return "".join(buffers) + return ''.join(buffers) buf.seek(0, 2) # seek end # reset _rbuf. we consume it via buf. @@ -1247,7 +1247,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): if size < 0: # Read until EOF buffers = [self._rbuf] - self._rbuf = "" + self._rbuf = '' if self._rbufsize <= 1: recv_size = self.default_bufsize else: @@ -1258,7 +1258,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): if not data: break buffers.append(data) - return "".join(buffers) + return ''.join(buffers) else: # Read until size bytes or EOF seen, whichever comes first data = self._rbuf @@ -1269,7 +1269,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buffers = [] if data: buffers.append(data) - self._rbuf = "" + self._rbuf = '' while True: left = size - buf_len recv_size = max(self._rbufsize, left) @@ -1283,7 +1283,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buffers[-1] = data[:left] break buf_len += n - return "".join(buffers) + return ''.join(buffers) def readline(self, size=-1): data = self._rbuf @@ -1291,14 +1291,14 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case - assert data == "" + assert data == '' buffers = [] - while data != "\n": + while data != '\n': data = self.recv(1) if not data: break buffers.append(data) - return "".join(buffers) + return ''.join(buffers) nl = data.find('\n') if nl >= 0: nl += 1 @@ -1307,7 +1307,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buffers = [] if data: buffers.append(data) - self._rbuf = "" + self._rbuf = '' while True: data = self.recv(self._rbufsize) if not data: @@ -1319,7 +1319,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): self._rbuf = data[nl:] buffers[-1] = data[:nl] break - return "".join(buffers) + return ''.join(buffers) else: # Read until size bytes or \n or EOF seen, whichever comes # first @@ -1335,7 +1335,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buffers = [] if data: buffers.append(data) - self._rbuf = "" + self._rbuf = '' while True: data = self.recv(self._rbufsize) if not data: @@ -1354,7 +1354,7 @@ class CP_makefile_PY2(getattr(socket, '_fileobject', object)): buffers[-1] = data[:left] break buf_len += n - return "".join(buffers) + return ''.join(buffers) CP_makefile = CP_makefile_PY2 if six.PY2 else CP_makefile_PY3 @@ -1379,8 +1379,8 @@ class HTTPConnection(object): def __init__(self, server, sock, makefile=CP_makefile): self.server = server self.socket = sock - self.rfile = makefile(sock, "rb", self.rbufsize) - self.wfile = makefile(sock, "wb", self.wbufsize) + self.rfile = makefile(sock, 'rb', self.rbufsize) + self.wfile = makefile(sock, 'wb', self.wbufsize) self.requests_seen = 0 def communicate(self): @@ -1425,18 +1425,18 @@ class HTTPConnection(object): # has already started being written. if req and not req.sent_headers: try: - req.simple_response("408 Request Timeout") + req.simple_response('408 Request Timeout') except FatalSSLAlert: # Close the connection. return except NoSSLError: self._handle_no_ssl() elif errnum not in socket_errors_to_ignore: - self.server.error_log("socket.error %s" % repr(errnum), + self.server.error_log('socket.error %s' % repr(errnum), level=logging.WARNING, traceback=True) if req and not req.sent_headers: try: - req.simple_response("500 Internal Server Error") + req.simple_response('500 Internal Server Error') except FatalSSLAlert: # Close the connection. return @@ -1455,7 +1455,7 @@ class HTTPConnection(object): self.server.error_log(repr(e), level=logging.ERROR, traceback=True) if req and not req.sent_headers: try: - req.simple_response("500 Internal Server Error") + req.simple_response('500 Internal Server Error') except FatalSSLAlert: # Close the connection. return @@ -1466,12 +1466,12 @@ class HTTPConnection(object): if not req or req.sent_headers: return # Unwrap wfile - self.wfile = CP_makefile(self.socket._sock, "wb", self.wbufsize) + self.wfile = CP_makefile(self.socket._sock, 'wb', self.wbufsize) msg = ( - "The client sent a plain HTTP request, but " - "this server only speaks HTTPS on this port." + 'The client sent a plain HTTP request, but ' + 'this server only speaks HTTPS on this port.' ) - req.simple_response("400 Bad Request", msg) + req.simple_response('400 Bad Request', msg) self.linger = True def close(self): @@ -1629,7 +1629,7 @@ class ThreadPool(object): for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: - worker.setName("CP Server " + worker.getName()) + worker.setName('CP Server ' + worker.getName()) worker.start() for worker in self._threads: while not worker.ready: @@ -1662,7 +1662,7 @@ class ThreadPool(object): def _spawn_worker(self): worker = WorkerThread(self.server) - worker.setName("CP Server " + worker.getName()) + worker.setName('CP Server ' + worker.getName()) worker.start() return worker @@ -1787,7 +1787,7 @@ class HTTPServer(object): """An HTTP server.""" - _bind_addr = "127.0.0.1" + _bind_addr = '127.0.0.1' _interrupt = None gateway = None @@ -1803,7 +1803,7 @@ class HTTPServer(object): server_name = None """The name of the server; defaults to socket.gethostname().""" - protocol = "HTTP/1.1" + protocol = 'HTTP/1.1' """The version string to write in the Status-Line of all HTTP responses. For example, "HTTP/1.1" is the default. This also limits the supported @@ -1821,7 +1821,7 @@ class HTTPServer(object): timeout = 10 """The timeout in seconds for accepted connections (default 10).""" - version = "CherryPy/" + cp_version + version = 'CherryPy/' + cp_version """A version string for the HTTPServer.""" software = None @@ -1872,9 +1872,9 @@ class HTTPServer(object): 'Run time': lambda s: (not s['Enabled']) and -1 or self.runtime(), 'Accepts': 0, 'Accepts/sec': lambda s: s['Accepts'] / self.runtime(), - 'Queue': lambda s: getattr(self.requests, "qsize", None), - 'Threads': lambda s: len(getattr(self.requests, "_threads", [])), - 'Threads Idle': lambda s: getattr(self.requests, "idle", None), + 'Queue': lambda s: getattr(self.requests, 'qsize', None), + 'Threads': lambda s: len(getattr(self.requests, '_threads', [])), + 'Threads Idle': lambda s: getattr(self.requests, 'idle', None), 'Socket Errors': 0, 'Requests': lambda s: (not s['Enabled']) and -1 or sum( [w['Requests'](w) for w in s['Worker Threads'].values()], 0), @@ -1893,7 +1893,7 @@ class HTTPServer(object): for w in s['Worker Threads'].values()], 0), 'Worker Threads': {}, } - logging.statistics["CherryPy HTTPServer %d" % id(self)] = self.stats + logging.statistics['CherryPy HTTPServer %d' % id(self)] = self.stats def runtime(self): if self._start_time is None: @@ -1902,7 +1902,7 @@ class HTTPServer(object): return self._run_time + (time.time() - self._start_time) def __str__(self): - return "%s.%s(%r)" % (self.__module__, self.__class__.__name__, + return '%s.%s(%r)' % (self.__module__, self.__class__.__name__, self.bind_addr) def _get_bind_addr(self): @@ -1922,7 +1922,7 @@ class HTTPServer(object): # '0.0.0.0', we deny both the empty string and None as values. raise ValueError("Host values of '' or None are not allowed. " "Use '0.0.0.0' (IPv4) or '::' (IPv6) instead " - "to listen on all active interfaces.") + 'to listen on all active interfaces.') self._bind_addr = value bind_addr = property( _get_bind_addr, @@ -1950,7 +1950,7 @@ class HTTPServer(object): self._interrupt = None if self.software is None: - self.software = "%s Server" % self.version + self.software = '%s Server' % self.version # Select the appropriate socket self.socket = None @@ -1973,7 +1973,7 @@ class HTTPServer(object): pass info = [ - (socket.AF_UNIX, socket.SOCK_STREAM, 0, "", self.bind_addr)] + (socket.AF_UNIX, socket.SOCK_STREAM, 0, '', self.bind_addr)] else: # AF_INET or AF_INET6 socket # Get the correct address family for our host (allows IPv6 @@ -1986,20 +1986,20 @@ class HTTPServer(object): except socket.gaierror: if ':' in self.bind_addr[0]: info = [(socket.AF_INET6, socket.SOCK_STREAM, - 0, "", self.bind_addr + (0, 0))] + 0, '', self.bind_addr + (0, 0))] else: info = [(socket.AF_INET, socket.SOCK_STREAM, - 0, "", self.bind_addr)] + 0, '', self.bind_addr)] if not self.socket: - msg = "No socket could be created" + msg = 'No socket could be created' for res in info: af, socktype, proto, canonname, sa = res try: self.bind(af, socktype, proto) break except socket.error as serr: - msg = "%s -- (%s: %s)" % (msg, sa, serr) + msg = '%s -- (%s: %s)' % (msg, sa, serr) if self.socket: self.socket.close() self.socket = None @@ -2022,7 +2022,7 @@ class HTTPServer(object): except (KeyboardInterrupt, SystemExit): raise except: - self.error_log("Error in HTTPServer.tick", level=logging.ERROR, + self.error_log('Error in HTTPServer.tick', level=logging.ERROR, traceback=True) if self.interrupt: @@ -2032,7 +2032,7 @@ class HTTPServer(object): if self.interrupt: raise self.interrupt - def error_log(self, msg="", level=20, traceback=False): + def error_log(self, msg='', level=20, traceback=False): # Override this in subclasses as desired sys.stderr.write(msg + '\n') sys.stderr.flush() @@ -2087,17 +2087,17 @@ class HTTPServer(object): try: s, ssl_env = self.ssl_adapter.wrap(s) except NoSSLError: - msg = ("The client sent a plain HTTP request, but " - "this server only speaks HTTPS on this port.") - buf = ["%s 400 Bad Request\r\n" % self.protocol, - "Content-Length: %s\r\n" % len(msg), - "Content-Type: text/plain\r\n\r\n", + msg = ('The client sent a plain HTTP request, but ' + 'this server only speaks HTTPS on this port.') + buf = ['%s 400 Bad Request\r\n' % self.protocol, + 'Content-Length: %s\r\n' % len(msg), + 'Content-Type: text/plain\r\n\r\n', msg] sock_to_make = s if six.PY3 else s._sock - wfile = makefile(sock_to_make, "wb", DEFAULT_BUFFER_SIZE) + wfile = makefile(sock_to_make, 'wb', DEFAULT_BUFFER_SIZE) try: - wfile.write(ntob("".join(buf))) + wfile.write(ntob(''.join(buf))) except socket.error: x = sys.exc_info()[1] if x.args[0] not in socket_errors_to_ignore: @@ -2169,8 +2169,8 @@ class HTTPServer(object): self.stop() self._interrupt = interrupt interrupt = property(_get_interrupt, _set_interrupt, - doc="Set this to an Exception instance to " - "interrupt the server.") + doc='Set this to an Exception instance to ' + 'interrupt the server.') def stop(self): """Gracefully shutdown a server that is serving forever.""" @@ -2179,7 +2179,7 @@ class HTTPServer(object): self._run_time += (time.time() - self._start_time) self._start_time = None - sock = getattr(self, "socket", None) + sock = getattr(self, 'socket', None) if sock: if not isinstance(self.bind_addr, six.string_types): # Touch our own socket to make accept() return immediately. @@ -2212,7 +2212,7 @@ class HTTPServer(object): except socket.error: if s: s.close() - if hasattr(sock, "close"): + if hasattr(sock, 'close'): sock.close() self.socket = None @@ -2244,7 +2244,7 @@ def get_ssl_adapter_class(name='builtin'): """Return an SSL adapter class for the given name.""" adapter = ssl_adapters[name.lower()] if isinstance(adapter, six.string_types): - last_dot = adapter.rfind(".") + last_dot = adapter.rfind('.') attr_name = adapter[last_dot + 1:] mod_path = adapter[:last_dot] @@ -2334,10 +2334,10 @@ class WSGIGateway(Gateway): try: for chunk in filter(None, response): if not isinstance(chunk, six.binary_type): - raise ValueError("WSGI Applications must yield bytes") + raise ValueError('WSGI Applications must yield bytes') self.write(chunk) finally: - if hasattr(response, "close"): + if hasattr(response, 'close'): response.close() def start_response(self, status, headers, exc_info=None): @@ -2347,8 +2347,8 @@ class WSGIGateway(Gateway): # "The application may call start_response more than once, # if and only if the exc_info argument is provided." if self.started_response and not exc_info: - raise AssertionError("WSGI start_response called a second " - "time with no exc_info.") + raise AssertionError('WSGI start_response called a second ' + 'time with no exc_info.') self.started_response = True # "if exc_info is provided, and the HTTP headers have already been @@ -2365,10 +2365,10 @@ class WSGIGateway(Gateway): for k, v in headers: if not isinstance(k, str): raise TypeError( - "WSGI response header key %r is not of type str." % k) + 'WSGI response header key %r is not of type str.' % k) if not isinstance(v, str): raise TypeError( - "WSGI response header value %r is not of type str." % v) + 'WSGI response header value %r is not of type str.' % v) if k.lower() == 'content-length': self.remaining_bytes_out = int(v) out_header = ntob(k), ntob(v) @@ -2387,7 +2387,7 @@ class WSGIGateway(Gateway): if six.PY2: return status if not isinstance(status, str): - raise TypeError("WSGI response status is not of type str.") + raise TypeError('WSGI response status is not of type str.') return status.encode('ISO-8859-1') def write(self, chunk): @@ -2397,7 +2397,7 @@ class WSGIGateway(Gateway): data from the iterable returned by the WSGI application). """ if not self.started_response: - raise AssertionError("WSGI write called before start_response.") + raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out @@ -2405,9 +2405,9 @@ class WSGIGateway(Gateway): if not self.req.sent_headers: # Whew. We can send a 500 to the client. self.req.simple_response( - "500 Internal Server Error", - "The requested resource returned more bytes than the " - "declared Content-Length.") + '500 Internal Server Error', + 'The requested resource returned more bytes than the ' + 'declared Content-Length.') else: # Dang. We have probably already sent data. Truncate the chunk # to fit (so the client doesn't hang) and raise an error later. @@ -2423,7 +2423,7 @@ class WSGIGateway(Gateway): rbo -= chunklen if rbo < 0: raise ValueError( - "Response body exceeds the declared Content-Length.") + 'Response body exceeds the declared Content-Length.') class WSGIGateway_10(WSGIGateway): @@ -2461,23 +2461,23 @@ class WSGIGateway_10(WSGIGateway): if isinstance(req.server.bind_addr, six.string_types): # AF_UNIX. This isn't really allowed by WSGI, which doesn't # address unix domain sockets. But it's better than nothing. - env["SERVER_PORT"] = "" + env['SERVER_PORT'] = '' else: - env["SERVER_PORT"] = str(req.server.bind_addr[1]) + env['SERVER_PORT'] = str(req.server.bind_addr[1]) # Request headers env.update( - ("HTTP_" + bton(k).upper().replace("-", "_"), bton(v)) + ('HTTP_' + bton(k).upper().replace('-', '_'), bton(v)) for k, v in req.inheaders.items() ) # CONTENT_TYPE/CONTENT_LENGTH - ct = env.pop("HTTP_CONTENT_TYPE", None) + ct = env.pop('HTTP_CONTENT_TYPE', None) if ct is not None: - env["CONTENT_TYPE"] = ct - cl = env.pop("HTTP_CONTENT_LENGTH", None) + env['CONTENT_TYPE'] = ct + cl = env.pop('HTTP_CONTENT_LENGTH', None) if cl is not None: - env["CONTENT_LENGTH"] = cl + env['CONTENT_LENGTH'] = cl if req.conn.ssl_env: env.update(req.conn.ssl_env) @@ -2503,13 +2503,13 @@ class WSGIGateway_u0(WSGIGateway_10): # Request-URI enc = env.setdefault(six.u('wsgi.url_encoding'), six.u('utf-8')) try: - env["PATH_INFO"] = req.path.decode(enc) - env["QUERY_STRING"] = req.qs.decode(enc) + env['PATH_INFO'] = req.path.decode(enc) + env['QUERY_STRING'] = req.qs.decode(enc) except UnicodeDecodeError: # Fall back to latin 1 so apps can transcode if needed. env['wsgi.url_encoding'] = 'ISO-8859-1' - env["PATH_INFO"] = env_10["PATH_INFO"] - env["QUERY_STRING"] = env_10["QUERY_STRING"] + env['PATH_INFO'] = env_10['PATH_INFO'] + env['QUERY_STRING'] = env_10['QUERY_STRING'] env.update(map(self._decode_value, self.items())) @@ -2554,16 +2554,16 @@ class WSGIPathInfoDispatcher(object): # The path_prefix strings must start, but not end, with a slash. # Use "" instead of "/". - self.apps = [(p.rstrip("/"), a) for p, a in apps] + self.apps = [(p.rstrip('/'), a) for p, a in apps] def __call__(self, environ, start_response): - path = environ["PATH_INFO"] or "/" + path = environ['PATH_INFO'] or '/' for p, app in self.apps: # The apps list should be sorted by length, descending. - if path.startswith(p + "/") or path == p: + if path.startswith(p + '/') or path == p: environ = environ.copy() - environ["SCRIPT_NAME"] = environ["SCRIPT_NAME"] + p - environ["PATH_INFO"] = path[len(p):] + environ['SCRIPT_NAME'] = environ['SCRIPT_NAME'] + p + environ['PATH_INFO'] = path[len(p):] return app(environ, start_response) start_response('404 Not Found', [('Content-Type', 'text/plain'), diff --git a/cherrypy/wsgiserver/ssl_builtin.py b/cherrypy/wsgiserver/ssl_builtin.py index c8585b71..3f6cb62f 100644 --- a/cherrypy/wsgiserver/ssl_builtin.py +++ b/cherrypy/wsgiserver/ssl_builtin.py @@ -44,7 +44,7 @@ class BuiltinSSLAdapter(wsgiserver.SSLAdapter): def __init__(self, certificate, private_key, certificate_chain=None): if ssl is None: - raise ImportError("You must install the ssl module to use HTTPS.") + raise ImportError('You must install the ssl module to use HTTPS.') self.certificate = certificate self.private_key = private_key self.certificate_chain = certificate_chain @@ -94,8 +94,8 @@ class BuiltinSSLAdapter(wsgiserver.SSLAdapter): """Create WSGI environ entries to be merged into each request.""" cipher = sock.cipher() ssl_environ = { - "wsgi.url_scheme": "https", - "HTTPS": "on", + 'wsgi.url_scheme': 'https', + 'HTTPS': 'on', 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0] # SSL_VERSION_INTERFACE string The mod_ssl program version diff --git a/cherrypy/wsgiserver/ssl_pyopenssl.py b/cherrypy/wsgiserver/ssl_pyopenssl.py index 54dff6de..a1c09d89 100644 --- a/cherrypy/wsgiserver/ssl_pyopenssl.py +++ b/cherrypy/wsgiserver/ssl_pyopenssl.py @@ -70,15 +70,15 @@ class SSL_fileobject(wsgiserver.CP_makefile): time.sleep(self.ssl_retry) except SSL.SysCallError as e: if is_reader and e.args == (-1, 'Unexpected EOF'): - return "" + return '' errnum = e.args[0] if is_reader and errnum in wsgiserver.socket_errors_to_ignore: - return "" + return '' raise socket.error(errnum) except SSL.Error as e: if is_reader and e.args == (-1, 'Unexpected EOF'): - return "" + return '' thirdarg = None try: @@ -95,7 +95,7 @@ class SSL_fileobject(wsgiserver.CP_makefile): raise if time.time() - start > self.ssl_timeout: - raise socket.timeout("timed out") + raise socket.timeout('timed out') def recv(self, size): return self._safe_call(True, super(SSL_fileobject, self).recv, size) @@ -166,7 +166,7 @@ class pyOpenSSLAdapter(wsgiserver.SSLAdapter): def __init__(self, certificate, private_key, certificate_chain=None): if SSL is None: - raise ImportError("You must install pyOpenSSL to use HTTPS.") + raise ImportError('You must install pyOpenSSL to use HTTPS.') self.context = None self.certificate = certificate @@ -199,7 +199,7 @@ class pyOpenSSLAdapter(wsgiserver.SSLAdapter): def get_environ(self): """Return WSGI environ entries to be merged into each request.""" ssl_environ = { - "HTTPS": "on", + 'HTTPS': 'on', # pyOpenSSL doesn't provide access to any of these AFAICT # 'SSL_PROTOCOL': 'SSLv2', # SSL_CIPHER string The cipher specification name @@ -220,8 +220,8 @@ class pyOpenSSLAdapter(wsgiserver.SSLAdapter): # Validity of server's certificate (end time), }) - for prefix, dn in [("I", cert.get_issuer()), - ("S", cert.get_subject())]: + for prefix, dn in [('I', cert.get_issuer()), + ('S', cert.get_subject())]: # X509Name objects don't seem to have a way to get the # complete DN string. Use str() and slice it instead, # because str(dn) == "<X509Name object '/C=US/ST=...'>" @@ -233,9 +233,9 @@ class pyOpenSSLAdapter(wsgiserver.SSLAdapter): # The DN should be of the form: /k1=v1/k2=v2, but we must allow # for any value to contain slashes itself (in a URL). while dnstr: - pos = dnstr.rfind("=") + pos = dnstr.rfind('=') dnstr, value = dnstr[:pos], dnstr[pos + 1:] - pos = dnstr.rfind("/") + pos = dnstr.rfind('/') dnstr, key = dnstr[:pos], dnstr[pos + 1:] if key and value: wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key) |