diff options
author | Lakin Wecker <none@none> | 2009-06-01 16:43:59 +0000 |
---|---|---|
committer | Lakin Wecker <none@none> | 2009-06-01 16:43:59 +0000 |
commit | bcac4e137da9675a5ba2ba4dfe0404288749e33a (patch) | |
tree | 9640ef6ef03106e218e9623e852e4c4f5fd42f8e | |
parent | 03f15ebb2a21e24a2a7458b9022ce05e89137fa4 (diff) | |
download | cherrypy-git-bcac4e137da9675a5ba2ba4dfe0404288749e33a.tar.gz |
trunk - adding a py3util module that will normalize as many differences between this branch and the python3 branch as it can. First it includes a py3print call who's signature matches that of print in python3. Also removed a few byte strings of the form b''
31 files changed, 148 insertions, 131 deletions
diff --git a/cherrypy/__init__.py b/cherrypy/__init__.py index 2dd9ec0c..6551e481 100644 --- a/cherrypy/__init__.py +++ b/cherrypy/__init__.py @@ -552,6 +552,7 @@ def url(path="", qs="", script_name=None, base=None, relative=None): return newurl +from cherrypy.py3util import py3print # import _cpconfig last so it can reference other top-level objects from cherrypy import _cpconfig diff --git a/cherrypy/lib/auth.py b/cherrypy/lib/auth.py index 11a96735..1ef87f45 100644 --- a/cherrypy/lib/auth.py +++ b/cherrypy/lib/auth.py @@ -13,13 +13,13 @@ def check_auth(users, encrypt=None, realm=None): if not encrypt: encrypt = httpauth.DIGEST_AUTH_ENCODERS[httpauth.MD5] - if callable(users): + if hasattr(users, '__call__'): try: # backward compatibility users = users() # expect it to return a dictionary 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) @@ -28,7 +28,7 @@ def check_auth(users, encrypt=None, realm=None): 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) diff --git a/cherrypy/lib/auth_basic.py b/cherrypy/lib/auth_basic.py index dc26b370..f8e7a18a 100644 --- a/cherrypy/lib/auth_basic.py +++ b/cherrypy/lib/auth_basic.py @@ -20,7 +20,7 @@ app_config = { '/' : basic_auth } __author__ = 'visteya' __date__ = 'April 2009' - +import binascii import base64 import cherrypy @@ -61,7 +61,7 @@ def basic_auth(realm, checkpassword): """ if '"' in realm: - raise ValueError, 'Realm cannot contain the " (quote) character.' + raise ValueError('Realm cannot contain the " (quote) character.') auth_header = cherrypy.request.headers.get('authorization') if auth_header is not None: diff --git a/cherrypy/lib/caching.py b/cherrypy/lib/caching.py index 7659b6d0..3405e097 100644 --- a/cherrypy/lib/caching.py +++ b/cherrypy/lib/caching.py @@ -5,7 +5,7 @@ import time import cherrypy from cherrypy.lib import cptools, httputil -class VaryHeaderAwareStore(): +class VaryHeaderAwareStore: """ A cache store that honors the Vary headers and keeps a separate cached copy for each. diff --git a/cherrypy/lib/covercp.py b/cherrypy/lib/covercp.py index 64bf23bc..aa6d9904 100644 --- a/cherrypy/lib/covercp.py +++ b/cherrypy/lib/covercp.py @@ -185,7 +185,7 @@ def _percent(statements, missing): def _show_branch(root, base, path, pct=0, showpct=False, exclude=""): # Show the directory name and any of our children - dirs = [k for k, v in root.iteritems() if v] + dirs = [k for k, v in root.items() if v] dirs.sort() for name in dirs: newpath = os.path.join(path, name) @@ -202,7 +202,7 @@ def _show_branch(root, base, path, pct=0, showpct=False, exclude=""): # Now list the files if path.lower().startswith(base): relpath = path[len(base):] - files = [k for k, v in root.iteritems() if not v] + files = [k for k, v in root.items() if not v] files.sort() for name in files: newpath = os.path.join(path, name) @@ -252,7 +252,7 @@ def get_tree(base, exclude): """Return covered module names as a nested dict.""" tree = {} coverage.get_ready() - runs = coverage.cexecuted.keys() + runs = list(coverage.cexecuted.keys()) if runs: for path in runs: if not _skip_file(path, exclude) and not os.path.isdir(path): diff --git a/cherrypy/lib/cptools.py b/cherrypy/lib/cptools.py index 8c0f9bca..cfa607b0 100644 --- a/cherrypy/lib/cptools.py +++ b/cherrypy/lib/cptools.py @@ -240,7 +240,7 @@ Message: %(error_msg)s if error_msg: body = self.login_screen(from_page, username, error_msg) cherrypy.response.body = body - if cherrypy.response.headers.has_key("Content-Length"): + if "Content-Length" in cherrypy.response.headers: # Delete Content-Length header so finalize() recalcs it. del cherrypy.response.headers["Content-Length"] return True @@ -269,7 +269,7 @@ Message: %(error_msg)s sess[self.session_key] = username = self.anonymous() if not username: cherrypy.response.body = self.login_screen(cherrypy.url(qs=request.query_string)) - if cherrypy.response.headers.has_key("Content-Length"): + if "Content-Length" in cherrypy.response.headers: # Delete Content-Length header so finalize() recalcs it. del cherrypy.response.headers["Content-Length"] return True @@ -297,7 +297,7 @@ Message: %(error_msg)s def session_auth(**kwargs): sa = SessionAuth() - for k, v in kwargs.iteritems(): + for k, v in kwargs.items(): setattr(sa, k, v) return sa.run() session_auth.__doc__ = """Session authentication hook. diff --git a/cherrypy/lib/httpauth.py b/cherrypy/lib/httpauth.py index 285efe57..7ec636aa 100644 --- a/cherrypy/lib/httpauth.py +++ b/cherrypy/lib/httpauth.py @@ -142,17 +142,17 @@ def _parseDigestAuthorization (auth_params): # Check for required parameters required = ["username", "realm", "nonce", "uri", "response"] for k in required: - if not params.has_key(k): + if k not in params: return None # If qop is sent then cnonce and nc MUST be present - if params.has_key("qop") and not (params.has_key("cnonce") \ - and params.has_key("nc")): + 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 (params.has_key("cnonce") or params.has_key("nc")) and \ - not params.has_key("qop"): + if ("cnonce" in params or "nc" in params) and \ + "qop" not in params: return None return params diff --git a/cherrypy/py3util.py b/cherrypy/py3util.py new file mode 100644 index 00000000..49387e2c --- /dev/null +++ b/cherrypy/py3util.py @@ -0,0 +1,12 @@ +""" +A simple module that helps unify the code between a python2 and python3 library. +""" +import sys + +def py3print(*args, **kwargs): + sep = kwargs.get('sep', ' ') + end = kwargs.get('end', '\n') + file = kwargs.get('file', sys.stdout) + output = sep.join(['%s' % arg for arg in args]) + end + file.write(output) + diff --git a/cherrypy/test/benchmark.py b/cherrypy/test/benchmark.py index aaa692cd..05667721 100644 --- a/cherrypy/test/benchmark.py +++ b/cherrypy/test/benchmark.py @@ -217,7 +217,7 @@ Finished 1000 requests try: self.output = _cpmodpy.read_process(AB_PATH or "ab", self.args()) except: - print _cperror.format_exc() + cherrypy.py3print(_cperror.format_exc()) raise for attr, name, pattern in self.parse_patterns: @@ -237,7 +237,7 @@ if sys.platform in ("win32",): def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads): sess = ABSession(path) - attrs, names, patterns = zip(*sess.parse_patterns) + attrs, names, patterns = list(zip(*sess.parse_patterns)) avg = dict.fromkeys(attrs, 0.0) rows = [('threads',) + names] @@ -258,7 +258,7 @@ def thread_report(path=SCRIPT_NAME + "/hello", concurrency=safe_threads): def size_report(sizes=(10, 100, 1000, 10000, 100000, 100000000), concurrency=50): sess = ABSession(concurrency=concurrency) - attrs, names, patterns = zip(*sess.parse_patterns) + attrs, names, patterns = list(zip(*sess.parse_patterns)) rows = [('bytes',) + names] for sz in sizes: sess.path = "%s/sizer?size=%s" % (SCRIPT_NAME, sz) @@ -272,25 +272,25 @@ def print_report(rows): lengths = [len(str(row[i])) for row in rows] widths.append(max(lengths)) for row in rows: - print + cherrypy.py3print() for i, val in enumerate(row): - print str(val).rjust(widths[i]), "|", - print + cherrypy.py3print(str(val).rjust(widths[i]), "|", end=' ') + cherrypy.py3print() def run_standard_benchmarks(): - print - print ("Client Thread Report (1000 requests, 14 byte response body, " + cherrypy.py3print() + cherrypy.py3print("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, " + cherrypy.py3print() + cherrypy.py3print("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, " + cherrypy.py3print() + cherrypy.py3print("Size Report (1000 requests, 50 client threads, " "%s server threads):" % cherrypy.server.thread_pool) print_report(size_report()) @@ -315,7 +315,7 @@ def startup_modpython(req=None): def run_modpython(use_wsgi=False): - print "Starting mod_python..." + cherrypy.py3print("Starting mod_python...") pyopts = [] # Pass the null and ab=path options through Apache @@ -350,11 +350,11 @@ if __name__ == '__main__': switches, args = getopt.getopt(sys.argv[1:], "", longopts) opts = dict(switches) except getopt.GetoptError: - print __doc__ + cherrypy.py3print(__doc__) sys.exit(2) if "--help" in opts: - print __doc__ + cherrypy.py3print(__doc__) sys.exit(0) if "--ab" in opts: @@ -365,23 +365,23 @@ if __name__ == '__main__': # 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/" % + cherrypy.py3print("You may now open http://127.0.0.1:%s%s/" % (port, SCRIPT_NAME)) if "--null" in opts: - print "Using null Request object" + cherrypy.py3print("Using null Request object") else: def run(): end = time.time() - start - print "Started in %s seconds" % end + cherrypy.py3print("Started in %s seconds" % end) if "--null" in opts: - print "\nUsing null Request object" + cherrypy.py3print("\nUsing null Request object") try: run_standard_benchmarks() finally: cherrypy.engine.exit() - print "Starting CherryPy app server..." + cherrypy.py3print("Starting CherryPy app server...") class NullWriter(object): """Suppresses the printing of socket errors.""" diff --git a/cherrypy/test/helper.py b/cherrypy/test/helper.py index 7d34947d..6f9d18b5 100644 --- a/cherrypy/test/helper.py +++ b/cherrypy/test/helper.py @@ -75,7 +75,7 @@ class CPWebCase(webtest.WebCase): esc('<pre id="traceback">') + '(.*)' + esc('</pre>')) m = re.match(epage, self.body, re.DOTALL) if not m: - self._handlewebError('Error page does not match\n' + page) + self._handlewebError('Error page does not match; expected:\n' + page) return # Now test the pattern against the traceback diff --git a/cherrypy/test/logtest.py b/cherrypy/test/logtest.py index 7cec7d1b..78d7a740 100644 --- a/cherrypy/test/logtest.py +++ b/cherrypy/test/logtest.py @@ -41,36 +41,36 @@ class LogCase(object): markerPrefix = "test suite marker: " def _handleLogError(self, msg, data, marker, pattern): - print - print " ERROR:", msg + cherrypy.py3print() + cherrypy.py3print(" ERROR:", 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 >> " - print p, - # ARGH! + cherrypy.py3print(p, end=' ') + # ARGH sys.stdout.flush() while True: i = getchar().upper() if i not in "MPLIRX": continue - print i.upper() # Also prints new line + cherrypy.py3print(i.upper()) # Also prints new line 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 - print "<-- More -->\r", + cherrypy.py3print("<-- More -->\r", end=' ') m = getchar().lower() # Erase our "More" prompt - print " \r", + cherrypy.py3print(" \r", end=' ') if m == "q": break - print line.rstrip() + cherrypy.py3print(line.rstrip()) elif i == "M": - print repr(marker or self.lastmarker) + cherrypy.py3print(repr(marker or self.lastmarker)) elif i == "P": - print repr(pattern) + cherrypy.py3print(repr(pattern)) elif i == "I": # return without raising the normal exception return @@ -78,7 +78,7 @@ class LogCase(object): raise self.failureException(msg) elif i == "X": self.exit() - print p, + cherrypy.py3print(p, end=' ') def exit(self): sys.exit() diff --git a/cherrypy/test/modfcgid.py b/cherrypy/test/modfcgid.py index 3a7c0749..e97ebf88 100644 --- a/cherrypy/test/modfcgid.py +++ b/cherrypy/test/modfcgid.py @@ -110,7 +110,7 @@ class ServerControl(test.LocalServer): result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf) if result: - print result + cherrypy.py3print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" diff --git a/cherrypy/test/modpy.py b/cherrypy/test/modpy.py index f6659475..a39238f4 100644 --- a/cherrypy/test/modpy.py +++ b/cherrypy/test/modpy.py @@ -116,7 +116,7 @@ class ServerControl(object): result = read_process(APACHE_PATH, "-k start -f %s" % mpconf) if result: - print result + cherrypy.py3print(result) def stop(self): """Gracefully shutdown a server that is serving forever.""" diff --git a/cherrypy/test/modwsgi.py b/cherrypy/test/modwsgi.py index ef35f481..6e578d3f 100644 --- a/cherrypy/test/modwsgi.py +++ b/cherrypy/test/modwsgi.py @@ -115,7 +115,7 @@ class ServerControl(object): result = read_process(APACHE_PATH, "-k start -f %s" % mpconf) if result: - print result + cherrypy.py3print(result) # Make a request so mod_wsgi starts up our app. # If we don't, concurrent initial requests will 404. diff --git a/cherrypy/test/test.py b/cherrypy/test/test.py index 65af1a0d..86c08714 100644 --- a/cherrypy/test/test.py +++ b/cherrypy/test/test.py @@ -40,15 +40,15 @@ class TestHarness(object): """Run the test harness (using the given [global] conf).""" import cherrypy v = sys.version.split()[0] - print "Python version used to run this test script:", v - print "CherryPy version", cherrypy.__version__ + cherrypy.py3print("Python version used to run this test script:", v) + cherrypy.py3print("CherryPy version", cherrypy.__version__) if self.scheme == "https": ssl = "(ssl)" else: ssl = "" - print "HTTP server version", self.protocol, ssl - print "PID:", os.getpid() - print + cherrypy.py3print("HTTP server version", self.protocol, ssl) + cherrypy.py3print("PID:", os.getpid()) + cherrypy.py3print() if isinstance(conf, basestring): parser = cherrypy.config._Parser() @@ -75,8 +75,8 @@ class TestHarness(object): webtest.WebCase.interactive = self.interactive if self.scheme == "https": webtest.WebCase.HTTP_CONN = httplib.HTTPSConnection - print - print "Running tests:", self.server + cherrypy.py3print() + cherrypy.py3print("Running tests:", self.server) return helper.run_test_suite(self.tests, baseconf, self.server) @@ -242,9 +242,10 @@ class CommandLineParser(object): if o in self.available_tests and o not in self.tests: self.tests.append(o) + import cherrypy if self.cover and self.profile: # Print error message and exit - print ('Error: you cannot run the profiler and the ' + cherrypy.py3print('Error: you cannot run the profiler and the ' 'coverage tool at the same time.') sys.exit(2) @@ -257,20 +258,21 @@ class CommandLineParser(object): def help(self): """Print help for test.py command-line options.""" - print """CherryPy Test Program + import cherrypy + cherrypy.py3print("""CherryPy Test Program Usage: test.py --help --server=* --host=%s --port=%s --1.0 --ssl --cover --basedir=path --profile --validate --conquer --dumb --tests** - """ % (self.__class__.host, self.__class__.port) - print ' * servers:' - for name, val in self.available_servers.iteritems(): + """ % (self.__class__.host, self.__class__.port)) + cherrypy.py3print(' * servers:') + for name, val in self.available_servers.items(): if name == self.default_server: - print ' --server=%s: %s (default)' % (name, val) + cherrypy.py3print(' --server=%s: %s (default)' % (name, val)) else: - print ' --server=%s: %s' % (name, val) + cherrypy.py3print(' --server=%s: %s' % (name, val)) - print """ + cherrypy.py3print(""" --host=<name or IP addr>: use a host other than the default (%s). Not yet available with mod_python servers. @@ -284,11 +286,11 @@ class CommandLineParser(object): --validate: use wsgiref.validate (builtin in Python 2.5). --conquer: use wsgiconq (which uses pyconquer) to trace calls. --dumb: turn off the interactive output features. - """ % (self.__class__.host, self.__class__.port) + """ % (self.__class__.host, self.__class__.port)) - print ' ** tests:' + cherrypy.py3print(' ** tests:') for name in self.available_tests: - print ' --' + name + cherrypy.py3print(' --' + name) def start_coverage(self): """Start the coverage tool. @@ -325,12 +327,13 @@ class CommandLineParser(object): if self.coverage: self.coverage.save() self.report_coverage() - print ("run cherrypy/lib/covercp.py as a script to serve " + cherrypy.py3print("run cherrypy/lib/covercp.py as a script to serve " "coverage results on port 8080") def report_coverage(self): """Print a summary from the code coverage tool.""" + import cherrypy basedir = self.basedir if basedir is None: # Assume we want to cover everything in "../../cherrypy/" @@ -347,8 +350,8 @@ class CommandLineParser(object): total_statements = 0 total_executed = 0 - print - print "CODE COVERAGE (this might take a while)", + cherrypy.py3print() + cherrypy.py3print("CODE COVERAGE (this might take a while)", end=' ') for morf in morfs: sys.stdout.write(".") sys.stdout.flush() @@ -371,7 +374,7 @@ class CommandLineParser(object): if total_statements > 0: pc = 100.0 * total_executed / total_statements - print ("\nTotal: %s Covered: %s Percent: %2d%%" + cherrypy.py3print("\nTotal: %s Covered: %s Percent: %2d%%" % (total_statements, total_executed, pc)) def run(self, conf=None): @@ -421,8 +424,8 @@ class CommandLineParser(object): success = h.run(conf) if self.profile: - print - print ("run /cherrypy/lib/profiler.py as a script to serve " + cherrypy.py3print() + cherrypy.py3print("run /cherrypy/lib/profiler.py as a script to serve " "profiling results on port 8080") if self.cover: @@ -491,8 +494,9 @@ def run(): clp = CommandLineParser(testList) success = clp.run() + import cherrypy if clp.interactive: - print + cherrypy.py3print() raw_input('hit enter') sys.exit(success) diff --git a/cherrypy/test/test_config_server.py b/cherrypy/test/test_config_server.py index 9b2e217b..d1afc7f6 100644 --- a/cherrypy/test/test_config_server.py +++ b/cherrypy/test/test_config_server.py @@ -79,7 +79,7 @@ class ServerConfigTests(helper.CPWebCase): def testMaxRequestSizePerHandler(self): if getattr(cherrypy.server, "using_apache", False): - print "skipped due to known Apache differences...", + cherrypy.py3print("skipped due to known Apache differences...", end=' ') return self.getPage('/tinyupload?maxlen=100', method="POST", body="x" * 100) @@ -90,7 +90,7 @@ class ServerConfigTests(helper.CPWebCase): def testMaxRequestSize(self): if getattr(cherrypy.server, "using_apache", False): - print "skipped due to known Apache differences...", + cherrypy.py3print("skipped due to known Apache differences...", end=' ') return for size in (500, 5000, 50000): diff --git a/cherrypy/test/test_conn.py b/cherrypy/test/test_conn.py index 639d9b5c..6da82aae 100644 --- a/cherrypy/test/test_conn.py +++ b/cherrypy/test/test_conn.py @@ -92,7 +92,7 @@ class ConnectionCloseTests(helper.CPWebCase): def test_HTTP11(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -247,7 +247,7 @@ class PipelineTests(helper.CPWebCase): def test_HTTP11_Timeout(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -334,7 +334,7 @@ class PipelineTests(helper.CPWebCase): def test_HTTP11_pipelining(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -372,7 +372,7 @@ class PipelineTests(helper.CPWebCase): def test_100_Continue(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -427,7 +427,7 @@ class ConnectionTests(helper.CPWebCase): def test_readall_or_close(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -499,7 +499,7 @@ class ConnectionTests(helper.CPWebCase): def test_No_Message_Body(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -529,13 +529,13 @@ class ConnectionTests(helper.CPWebCase): def test_Chunked_Encoding(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return if (hasattr(self, 'harness') and "modpython" in self.harness.__class__.__name__.lower()): # mod_python forbids chunked encoding - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" diff --git a/cherrypy/test/test_core.py b/cherrypy/test/test_core.py index c2c4c34f..10a60e88 100644 --- a/cherrypy/test/test_core.py +++ b/cherrypy/test/test_core.py @@ -568,7 +568,7 @@ class CoreRequestHandlingTest(helper.CPWebCase): def test_expose_decorator(self): if not sys.version_info >= (2, 5): - print "skipped (Python 2.5+ only)", + cherrypy.py3print("skipped (Python 2.5+ only)", end=' ') return # Test @expose diff --git a/cherrypy/test/test_http.py b/cherrypy/test/test_http.py index 25098235..f9ebcdc6 100644 --- a/cherrypy/test/test_http.py +++ b/cherrypy/test/test_http.py @@ -86,7 +86,7 @@ class HTTPTests(helper.CPWebCase): self.body = response.fp.read() self.status = str(response.status) self.assertStatus(200) - self.assertBody(b'Hello world!') + self.assertBody('Hello world!') # Now send a message that has no Content-Length, but does send a body. # Verify that CP times out the socket and responds @@ -129,7 +129,7 @@ class HTTPTests(helper.CPWebCase): def test_malformed_request_line(self): if getattr(cherrypy.server, "using_apache", False): - print "skipped due to known Apache differences...", + cherrypy.py3print("skipped due to known Apache differences...", end=' ') return # Test missing version in Request-Line @@ -142,12 +142,12 @@ class HTTPTests(helper.CPWebCase): response = c.response_class(c.sock, strict=c.strict, method='GET') response.begin() self.assertEqual(response.status, 400) - self.assertEqual(response.fp.read(22), b"Malformed Request-Line") + self.assertEqual(response.fp.read(22), "Malformed Request-Line") c.close() def test_http_over_https(self): if self.scheme != 'https': - print "skipped (not running HTTPS)...", + cherrypy.py3print("skipped (not running HTTPS)...", end=' ') return # Try connecting without SSL. diff --git a/cherrypy/test/test_json.py b/cherrypy/test/test_json.py index b6da6c48..26a8ef1f 100644 --- a/cherrypy/test/test_json.py +++ b/cherrypy/test/test_json.py @@ -5,7 +5,7 @@ import cherrypy from cherrypy.lib.jsontools import json if json is None: - print "skipped (simplejson not found) ", + cherrypy.py3print("skipped (simplejson not found) ", end=' ') else: def setup_server(): class Root(object): diff --git a/cherrypy/test/test_request_obj.py b/cherrypy/test/test_request_obj.py index e6094f60..369ca5ec 100644 --- a/cherrypy/test/test_request_obj.py +++ b/cherrypy/test/test_request_obj.py @@ -697,7 +697,7 @@ class RequestObjectTests(helper.CPWebCase): def test_CONNECT_method(self): if getattr(cherrypy.server, "using_apache", False): - print "skipped due to known Apache differences...", + cherrypy.py3print("skipped due to known Apache differences...", end=' ') return self.getPage("/method/", method="CONNECT") diff --git a/cherrypy/test/test_session.py b/cherrypy/test/test_session.py index 4945ecfa..a258e3cf 100755 --- a/cherrypy/test/test_session.py +++ b/cherrypy/test/test_session.py @@ -236,7 +236,7 @@ class SessionTest(helper.CPWebCase): else: data_dict[index] = max(data_dict[index], int(body)) # Uncomment the following line to prove threads overlap. -## print index, +## cherrypy.py3print(index, end=' ') # Start <request_count> requests from each of # <client_thread_count> concurrent clients @@ -254,7 +254,7 @@ class SessionTest(helper.CPWebCase): expected = 1 + (client_thread_count * request_count) for e in errors: - print e + cherrypy.py3print(e) self.assertEqual(hitcount, expected) def test_3_Redirect(self): @@ -381,7 +381,7 @@ except (ImportError, socket.error): class MemcachedSessionTest(helper.CPWebCase): def test(self): - print "skipped", + cherrypy.py3print("skipped", end=' ') else: class MemcachedSessionTest(helper.CPWebCase): @@ -428,7 +428,7 @@ else: for i in xrange(request_count): self.getPage("/", cookies) # Uncomment the following line to prove threads overlap. -## print index, +## cherrypy.py3print(index, end=' ') if not self.body.isdigit(): self.fail(self.body) data_dict[index] = v = int(self.body) diff --git a/cherrypy/test/test_states.py b/cherrypy/test/test_states.py index f38effbd..7591baf7 100644 --- a/cherrypy/test/test_states.py +++ b/cherrypy/test/test_states.py @@ -209,7 +209,7 @@ class ServerStateTests(helper.CPWebCase): except BadStatusLine: pass else: - print self.body + cherrypy.py3print(self.body) self.fail("AssertionError: BadStatusLine not raised") engine.block() @@ -230,7 +230,7 @@ class ServerStateTests(helper.CPWebCase): self.assertBody("Hello World") # request.close is called async. while engine.timeout_monitor.servings: - print ".", + checks.py3print(".", end=' ') time.sleep(0.01) # Request a page that explicitly checks itself for deadlock. @@ -295,7 +295,7 @@ class PluginTests(helper.CPWebCase): def test_daemonize(self): if os.name not in ['posix']: - print "skipped (not on posix) ", + checks.py3print("skipped (not on posix) ", end=' ') return self.HOST = '127.0.0.1' self.PORT = 8081 @@ -333,7 +333,7 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGHUP except ImportError: - print "skipped (no SIGHUP) ", + checks.py3print("skipped (no SIGHUP) ", end=' ') return # Spawn the process. @@ -351,11 +351,11 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGHUP except ImportError: - print "skipped (no SIGHUP) ", + checks.py3print("skipped (no SIGHUP) ", end=' ') return if os.name not in ['posix']: - print "skipped (not on posix) ", + checks.py3print("skipped (not on posix) ", end=' ') return # Spawn the process and wait, when this returns, the original process @@ -387,13 +387,13 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGTERM except ImportError: - print "skipped (no SIGTERM) ", + checks.py3print("skipped (no SIGTERM) ", end=' ') return try: from os import kill except ImportError: - print "skipped (no os.kill) ", + checks.py3print("skipped (no os.kill) ", end=' ') return # Spawn a normal, undaemonized process. @@ -422,13 +422,13 @@ class SignalHandlingTests(helper.CPWebCase): try: from signal import SIGTERM except ImportError: - print "skipped (no SIGTERM) ", + checks.py3print("skipped (no SIGTERM) ", end=' ') return try: from os import kill except ImportError: - print "skipped (no os.kill) ", + checks.py3print("skipped (no os.kill) ", end=' ') return # Spawn a normal, undaemonized process. diff --git a/cherrypy/test/test_static.py b/cherrypy/test/test_static.py index 40098119..8ef49c7e 100644 --- a/cherrypy/test/test_static.py +++ b/cherrypy/test/test_static.py @@ -184,7 +184,7 @@ class StaticTest(helper.CPWebCase): def test_file_stream(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" @@ -223,7 +223,7 @@ class StaticTest(helper.CPWebCase): def test_file_stream_deadlock(self): if cherrypy.server.protocol_version != "HTTP/1.1": - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.PROTOCOL = "HTTP/1.1" diff --git a/cherrypy/test/test_tidy.py b/cherrypy/test/test_tidy.py index ef437eda..85a5bc40 100644 --- a/cherrypy/test/test_tidy.py +++ b/cherrypy/test/test_tidy.py @@ -49,7 +49,7 @@ class TidyTest(helper.CPWebCase): def test_Tidy_Tool(self): if not os.path.exists(tidy_path) and not os.path.exists(tidy_path + ".exe"): - print "skipped (tidy not found) ", + cherrypy.py3print("skipped (tidy not found) ", end=' ') return self.getPage('/validhtml') diff --git a/cherrypy/test/test_tools.py b/cherrypy/test/test_tools.py index a958f594..9a77315b 100644 --- a/cherrypy/test/test_tools.py +++ b/cherrypy/test/test_tools.py @@ -295,7 +295,7 @@ class ToolTests(helper.CPWebCase): httpserver = cherrypy.server.httpserver old_timeout = httpserver.timeout except (AttributeError, IndexError): - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return try: @@ -374,7 +374,7 @@ class ToolTests(helper.CPWebCase): def testToolWithConfig(self): if not sys.version_info >= (2, 5): - print "skipped (Python 2.5+ only)", + cherrypy.py3print("skipped (Python 2.5+ only)", end=' ') return self.getPage('/tooldecs/blah') diff --git a/cherrypy/test/test_wsgi_ns.py b/cherrypy/test/test_wsgi_ns.py index 9e50c46b..0832d476 100644 --- a/cherrypy/test/test_wsgi_ns.py +++ b/cherrypy/test/test_wsgi_ns.py @@ -76,7 +76,7 @@ class WSGI_Namespace_Test(helper.CPWebCase): def test_pipeline(self): if not cherrypy.server.httpserver: - print "skipped ", + cherrypy.py3print("skipped ", end=' ') return self.getPage("/") diff --git a/cherrypy/test/test_wsgi_vhost.py b/cherrypy/test/test_wsgi_vhost.py index 40e2abe4..f193676d 100644 --- a/cherrypy/test/test_wsgi_vhost.py +++ b/cherrypy/test/test_wsgi_vhost.py @@ -33,7 +33,7 @@ class WSGI_VirtualHost_Test(helper.CPWebCase): def test_welcome(self): if not cherrypy.server.using_wsgi: - print "skipped (not using WSGI)...", + cherrypy.py3print("skipped (not using WSGI)...", end=' ') return for year in xrange(1997, 2008): diff --git a/cherrypy/test/test_wsgiapps.py b/cherrypy/test/test_wsgiapps.py index 95d3ca00..f53966b2 100644 --- a/cherrypy/test/test_wsgiapps.py +++ b/cherrypy/test/test_wsgiapps.py @@ -89,7 +89,7 @@ This is a wsgi app running within CherryPy!''' def test_04_pure_wsgi(self): import cherrypy if not cherrypy.server.using_wsgi: - print "skipped (not using WSGI)...", + cherrypy.py3print("skipped (not using WSGI)...", end=' ') return self.getPage("/hosted/app1") self.assertHeader("Content-Type", "text/plain") @@ -98,7 +98,7 @@ This is a wsgi app running within CherryPy!''' def test_05_wrapped_cp_app(self): import cherrypy if not cherrypy.server.using_wsgi: - print "skipped (not using WSGI)...", + cherrypy.py3print("skipped (not using WSGI)...", end=' ') return self.getPage("/hosted/app2/") body = list("I'm a regular CherryPy page handler!") @@ -109,7 +109,7 @@ This is a wsgi app running within CherryPy!''' def test_06_empty_string_app(self): import cherrypy if not cherrypy.server.using_wsgi: - print "skipped (not using WSGI)...", + cherrypy.py3print("skipped (not using WSGI)...", end=' ') return self.getPage("/hosted/app3") self.assertHeader("Content-Type", "text/plain") diff --git a/cherrypy/test/webtest.py b/cherrypy/test/webtest.py index f8b45619..74c9a941 100644 --- a/cherrypy/test/webtest.py +++ b/cherrypy/test/webtest.py @@ -242,38 +242,38 @@ class WebCase(TestCase): console_height = 30 def _handlewebError(self, msg): - print - print " ERROR:", msg + cherrypy.py3print() + cherrypy.py3print(" ERROR:", 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 >> " - print p, + cherrypy.py3print(p, end=' ') # ARGH! sys.stdout.flush() while True: i = getchar().upper() if i not in "BHSUIRX": continue - print i.upper() # Also prints new line + cherrypy.py3print(i.upper()) # Also prints new line 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 - print "<-- More -->\r", + cherrypy.py3print("<-- More -->\r", end=' ') m = getchar().lower() # Erase our "More" prompt - print " \r", + cherrypy.py3print(" \r", end=' ') if m == "q": break - print line + cherrypy.py3print(line) elif i == "H": pprint.pprint(self.headers) elif i == "S": - print self.status + cherrypy.py3print(self.status) elif i == "U": - print self.url + cherrypy.py3print(self.url) elif i == "I": # return without raising the normal exception return @@ -281,7 +281,7 @@ class WebCase(TestCase): raise self.failureException(msg) elif i == "X": self.exit() - print p, + cherrypy.py3print(p, end=' ') def exit(self): sys.exit() @@ -589,7 +589,7 @@ def server_error(exc=None): return False else: ServerError.on = True - print - print "".join(traceback.format_exception(*exc)) + cherrypy.py3print() + cherrypy.py3print("".join(traceback.format_exception(*exc))) return True diff --git a/cherrypy/tutorial/bonus-sqlobject.py b/cherrypy/tutorial/bonus-sqlobject.py index 0c903611..257773d1 100644 --- a/cherrypy/tutorial/bonus-sqlobject.py +++ b/cherrypy/tutorial/bonus-sqlobject.py @@ -163,6 +163,6 @@ class ContactManager: reset.exposed = True -print "If you're running this application for the first time, please go to http://localhost:8080/reset once in order to create the database!" +cherrypy.py3print("If you're running this application for the first time, please go to http://localhost:8080/reset once in order to create the database!") cherrypy.quickstart(ContactManager()) |