diff options
Diffstat (limited to 'tests')
38 files changed, 707 insertions, 642 deletions
diff --git a/tests/cgiapp_data/error.cgi b/tests/cgiapp_data/error.cgi index 5afc9c9..e11c766 100755 --- a/tests/cgiapp_data/error.cgi +++ b/tests/cgiapp_data/error.cgi @@ -1,3 +1,3 @@ #!/usr/bin/env python -print 'hey you!' +print('hey you!') diff --git a/tests/cgiapp_data/form.cgi b/tests/cgiapp_data/form.cgi index 6d2e038..2181998 100755 --- a/tests/cgiapp_data/form.cgi +++ b/tests/cgiapp_data/form.cgi @@ -2,11 +2,11 @@ import cgi -print 'Content-type: text/plain' -print +print('Content-type: text/plain') +print('') form = cgi.FieldStorage() -print 'Filename:', form['up'].filename -print 'Name:', form['name'].value -print 'Content:', form['up'].file.read() +print('Filename: %s' % form['up'].filename) +print('Name: %s' % form['name'].value) +print('Content: %s' % form['up'].file.read()) diff --git a/tests/cgiapp_data/ok.cgi b/tests/cgiapp_data/ok.cgi index 8b8eb29..d03f0b9 100755 --- a/tests/cgiapp_data/ok.cgi +++ b/tests/cgiapp_data/ok.cgi @@ -1,6 +1,5 @@ #!/usr/bin/env python - -print 'Content-type: text/html; charset=UTF-8' -print 'Status: 200 Okay' -print -print 'This is the body' +print('Content-type: text/html; charset=UTF-8') +print('Status: 200 Okay') +print('') +print('This is the body') diff --git a/tests/cgiapp_data/stderr.cgi b/tests/cgiapp_data/stderr.cgi index 89dae0a..d2520b6 100755 --- a/tests/cgiapp_data/stderr.cgi +++ b/tests/cgiapp_data/stderr.cgi @@ -1,8 +1,8 @@ #!/usr/bin/env python - +from __future__ import print_function import sys -print 'Status: 500 Server Error' -print 'Content-type: text/html' -print -print 'There was an error' -print >> sys.stderr, 'some data on the error' +print('Status: 500 Server Error') +print('Content-type: text/html') +print() +print('There was an error') +print('some data on the error', file=sys.stderr) diff --git a/tests/test_auth/test_auth_cookie.py b/tests/test_auth/test_auth_cookie.py index d1db981..38e37b8 100644 --- a/tests/test_auth/test_auth_cookie.py +++ b/tests/test_auth/test_auth_cookie.py @@ -2,20 +2,14 @@ # This module is part of the Python Paste Project and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -import os from six.moves import xrange -try: - # Python 3 - from http.cookies import SimpleCookie -except ImportError: - # Python 2 - from Cookie import SimpleCookie +import six from paste.auth import cookie from paste.wsgilib import raw_interactive, dump_environ from paste.response import header_value from paste.httpexceptions import * - + def build(application,setenv, *args, **kwargs): def setter(environ, start_response): save = environ['paste.auth.cookie'].append @@ -41,7 +35,10 @@ def test_basic(key='key', val='bingles'): cookie = value.split(";")[0] (status,headers,content,errors) = \ raw_interactive(app,{'HTTP_COOKIE': cookie}) - assert ("%s: %s" % (key,val.replace("\n","\n "))) in content + expected = ("%s: %s" % (key,val.replace("\n","\n "))) + if six.PY3: + expected = expected.encode('utf8') + assert expected in content def test_roundtrip(): roundtrip = str('').join(map(chr, xrange(256))) diff --git a/tests/test_auth/test_auth_digest.py b/tests/test_auth/test_auth_digest.py index a821720..1d44038 100644 --- a/tests/test_auth/test_auth_digest.py +++ b/tests/test_auth/test_auth_digest.py @@ -4,16 +4,19 @@ from paste.auth.digest import * from paste.wsgilib import raw_interactive -from paste.response import header_value from paste.httpexceptions import * from paste.httpheaders import AUTHORIZATION, WWW_AUTHENTICATE, REMOTE_USER import os +import six def application(environ, start_response): content = REMOTE_USER(environ) start_response("200 OK",(('Content-Type', 'text/plain'), ('Content-Length', len(content)))) - return content + + if six.PY3: + content = content.encode('utf8') + return [content] realm = "tag:clarkevans.com,2005:testing" @@ -46,7 +49,7 @@ def check(username, password, path="/"): assert False, "Unexpected Status: %s" % status def test_digest(): - assert 'bing' == check("bing","gnib") + assert b'bing' == check("bing","gnib") assert check("bing","bad") is None # diff --git a/tests/test_cgiapp.py b/tests/test_cgiapp.py index 2887271..12cb2be 100644 --- a/tests/test_cgiapp.py +++ b/tests/test_cgiapp.py @@ -17,8 +17,8 @@ if sys.platform != 'win32' and not sys.platform.startswith('java'): def test_form(): app = TestApp(CGIApplication({}, script='form.cgi', path=[data_dir])) - res = app.post('', params={'name': 'joe'}, - upload_files=[('up', 'file.txt', 'x'*10000)]) + res = app.post('', params={'name': b'joe'}, + upload_files=[('up', 'file.txt', b'x'*10000)]) assert 'file.txt' in res assert 'joe' in res assert 'x'*10000 in res @@ -32,5 +32,5 @@ if sys.platform != 'win32' and not sys.platform.startswith('java'): res = app.get('', expect_errors=True) assert res.status == 500 assert 'error' in res - assert 'some data' in res.errors + assert b'some data' in res.errors diff --git a/tests/test_cgitb_catcher.py b/tests/test_cgitb_catcher.py index 788ede2..a63f7d8 100644 --- a/tests/test_cgitb_catcher.py +++ b/tests/test_cgitb_catcher.py @@ -11,7 +11,7 @@ def do_request(app, expect_status=500): res = testapp.get('', status=expect_status, expect_errors=True) return res - + ############################################################ ## Applications that raise exceptions @@ -31,7 +31,7 @@ def after_start_response_app(environ, start_response): def iter_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) - return yielder(['this', ' is ', ' a', None]) + return yielder([b'this', b' is ', b' a', None]) def yielder(args): for arg in args: @@ -46,7 +46,10 @@ def yielder(args): def test_makes_exception(): res = do_request(bad_app) print(res) - assert 'bad_app() takes no arguments (2 given' in res + if six.PY3: + assert 'bad_app() takes 0 positional arguments but 2 were given' in res + else: + assert 'bad_app() takes no arguments (2 given' in res assert 'iterator = application(environ, start_response_wrapper)' in res assert 'lint.py' in res assert 'cgitb_catcher.py' in res @@ -69,7 +72,7 @@ def test_iter_app(): print(res) assert 'None raises error' in res assert 'yielder' in res - - - + + + diff --git a/tests/test_config.py b/tests/test_config.py index ea6be75..8119157 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,13 +3,24 @@ from nose.tools import assert_raises from paste.config import CONFIG, ConfigMiddleware from paste.fixture import TestApp +import six test_key = 'test key' +def reset_config(): + while True: + try: + CONFIG._pop_object() + except IndexError: + break + def app_with_config(environ, start_response): start_response('200 OK', [('Content-type','text/plain')]) - return ['Variable is: %s\n' % CONFIG[test_key], + lines = ['Variable is: %s\n' % CONFIG[test_key], 'Variable is (in environ): %s' % environ['paste.config'][test_key]] + if six.PY3: + lines = [line.encode('utf8') for line in lines] + return lines class NestingAppWithConfig(object): def __init__(self, app): @@ -21,43 +32,54 @@ class NestingAppWithConfig(object): supplement = ['Nesting variable is: %s' % CONFIG[test_key], 'Nesting variable is (in environ): %s' % \ environ['paste.config'][test_key]] + if six.PY3: + supplement = [line.encode('utf8') for line in supplement] response.extend(supplement) return response def test_request_config(): - config = {test_key: 'test value'} - app = ConfigMiddleware(app_with_config, config) - res = TestApp(app).get('/') - assert 'Variable is: test value' in res - assert 'Variable is (in environ): test value' in res + try: + config = {test_key: 'test value'} + app = ConfigMiddleware(app_with_config, config) + res = TestApp(app).get('/') + assert 'Variable is: test value' in res + assert 'Variable is (in environ): test value' in res + finally: + reset_config() def test_request_config_multi(): - config = {test_key: 'test value'} - app = ConfigMiddleware(app_with_config, config) - config = {test_key: 'nesting value'} - app = ConfigMiddleware(NestingAppWithConfig(app), config) - res = TestApp(app).get('/') - assert 'Variable is: test value' in res - assert 'Variable is (in environ): test value' in res - assert 'Nesting variable is: nesting value' in res - print(res) - assert 'Nesting variable is (in environ): nesting value' in res + try: + config = {test_key: 'test value'} + app = ConfigMiddleware(app_with_config, config) + config = {test_key: 'nesting value'} + app = ConfigMiddleware(NestingAppWithConfig(app), config) + res = TestApp(app).get('/') + assert 'Variable is: test value' in res + assert 'Variable is (in environ): test value' in res + assert 'Nesting variable is: nesting value' in res + print(res) + assert 'Nesting variable is (in environ): nesting value' in res + finally: + reset_config() def test_process_config(request_app=test_request_config): - process_config = {test_key: 'bar', 'process_var': 'foo'} - CONFIG.push_process_config(process_config) + try: + process_config = {test_key: 'bar', 'process_var': 'foo'} + CONFIG.push_process_config(process_config) + + assert CONFIG[test_key] == 'bar' + assert CONFIG['process_var'] == 'foo' - assert CONFIG[test_key] == 'bar' - assert CONFIG['process_var'] == 'foo' + request_app() - request_app() + assert CONFIG[test_key] == 'bar' + assert CONFIG['process_var'] == 'foo' + CONFIG.pop_process_config() - assert CONFIG[test_key] == 'bar' - assert CONFIG['process_var'] == 'foo' - CONFIG.pop_process_config() - - assert_raises(AttributeError, lambda: 'process_var' not in CONFIG) - assert_raises(IndexError, CONFIG.pop_process_config) + assert_raises(AttributeError, lambda: 'process_var' not in CONFIG) + assert_raises(IndexError, CONFIG.pop_process_config) + finally: + reset_config() def test_process_config_multi(): test_process_config(test_request_config_multi) diff --git a/tests/test_doctests.py b/tests/test_doctests.py index 3db3857..875fbc2 100644 --- a/tests/test_doctests.py +++ b/tests/test_doctests.py @@ -1,4 +1,4 @@ -from paste.util import doctest24 as doctest +import doctest from paste.util.import_string import simple_import import os diff --git a/tests/test_errordocument.py b/tests/test_errordocument.py index c284b93..efeae61 100644 --- a/tests/test_errordocument.py +++ b/tests/test_errordocument.py @@ -4,11 +4,11 @@ from paste.recursive import RecursiveMiddleware def simple_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) - return ['requested page returned'] + return [b'requested page returned'] def not_found_app(environ, start_response): start_response("404 Not found", [('Content-type', 'text/plain')]) - return ['requested page returned'] + return [b'requested page returned'] def test_ok(): app = TestApp(simple_app) @@ -20,10 +20,10 @@ def test_ok(): def error_docs_app(environ, start_response): if environ['PATH_INFO'] == '/not_found': start_response("404 Not found", [('Content-type', 'text/plain')]) - return ['Not found'] + return [b'Not found'] elif environ['PATH_INFO'] == '/error': start_response("200 OK", [('Content-type', 'text/plain')]) - return ['Page not found'] + return [b'Page not found'] else: return simple_app(environ, start_response) @@ -68,7 +68,7 @@ def auth_docs_app(environ, start_response): return auth_required_app(environ, start_response) elif environ['PATH_INFO'] == '/auth_doc': start_response("200 OK", [('Content-type', 'text/html')]) - return ['<html>Login!</html>'] + return [b'<html>Login!</html>'] else: return simple_app(environ, start_response) @@ -80,7 +80,7 @@ def test_auth_docs_app(): res = app.get('/auth', status=401) assert res.header('content-type') == 'text/html' assert res.header('www-authenticate') == 'Basic realm="Foo"' - assert res.body == '<html>Login!</html>' + assert res.body == b'<html>Login!</html>' def test_bad_error(): def app(environ, start_response): diff --git a/tests/test_exceptions/test_error_middleware.py b/tests/test_exceptions/test_error_middleware.py index a34de73..95ab177 100644 --- a/tests/test_exceptions/test_error_middleware.py +++ b/tests/test_exceptions/test_error_middleware.py @@ -19,7 +19,7 @@ def do_request(app, expect_status=500): def clear_middleware(app): """ The fixture sets paste.throw_errors, which suppresses exactly what - we want to test in this case. This wrapper also strips exc_info + we want to test in this case. This wrapper also strips exc_info on the *first* call to start_response (but not the second, or subsequent calls. """ @@ -34,7 +34,7 @@ def clear_middleware(app): del environ['paste.throw_errors'] return app(environ, replacement) return clear_throw_errors - + ############################################################ ## Applications that raise exceptions @@ -57,7 +57,7 @@ def after_start_response_app(environ, start_response): def iter_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) - return yielder(['this', ' is ', ' a', None]) + return yielder([b'this', b' is ', b' a', None]) def yielder(args): for arg in args: @@ -73,15 +73,17 @@ def test_makes_exception(): res = do_request(bad_app) assert '<html' in res res = strip_html(str(res)) - #print res - assert 'bad_app() takes no arguments (2 given' in res + if six.PY3: + assert 'bad_app() takes 0 positional arguments but 2 were given' in res + else: + assert 'bad_app() takes no arguments (2 given' in res, repr(res) assert 'iterator = application(environ, start_response_wrapper)' in res assert 'paste.lint' in res assert 'paste.exceptions.errormiddleware' in res def test_unicode_exception(): res = do_request(unicode_bad_app) - + def test_start_res(): res = do_request(start_response_app) @@ -101,7 +103,7 @@ def test_iter_app(): #print res assert 'None raises error' in res assert 'yielder' in res - - - + + + diff --git a/tests/test_exceptions/test_formatter.py b/tests/test_exceptions/test_formatter.py index 3d5bdad..9c53a9a 100644 --- a/tests/test_exceptions/test_formatter.py +++ b/tests/test_exceptions/test_formatter.py @@ -1,10 +1,8 @@ from paste.exceptions import formatter from paste.exceptions import collector -from paste.util.quoting import strip_html import sys import os import difflib -import re class Mock(object): def __init__(self, **kw): @@ -153,7 +151,6 @@ def test_hide_after(): raise_error) except: result = format(f) - print(strip_html(result).encode('ascii', 'replace')) assert 'AABB' in result assert 'CCDD' not in result assert 'raise_error' in result diff --git a/tests/test_exceptions/test_httpexceptions.py b/tests/test_exceptions/test_httpexceptions.py index 08e23d4..24e00dd 100644 --- a/tests/test_exceptions/test_httpexceptions.py +++ b/tests/test_exceptions/test_httpexceptions.py @@ -8,8 +8,8 @@ Regression Test Suite """ from nose.tools import assert_raises from paste.httpexceptions import * -from paste.wsgilib import raw_interactive from paste.response import header_value +import six def test_HTTPMove(): @@ -30,8 +30,8 @@ def test_badapp(): start_response("200 OK",[]) raise HTTPBadRequest("Do not do this at home.") newapp = HTTPExceptionHandler(badapp) - assert 'Bad Request' in ''.join(newapp({'HTTP_ACCEPT': 'text/html'}, - (lambda a, b, c=None: None))) + assert b'Bad Request' in b''.join(newapp({'HTTP_ACCEPT': 'text/html'}, + (lambda a, b, c=None: None))) def test_unicode(): """ verify unicode output """ @@ -40,10 +40,10 @@ def test_unicode(): start_response("200 OK",[]) raise HTTPBadRequest(tstr) newapp = HTTPExceptionHandler(badapp) - assert tstr.encode("utf-8") in ''.join(newapp({'HTTP_ACCEPT': + assert tstr.encode("utf-8") in b''.join(newapp({'HTTP_ACCEPT': 'text/html'}, (lambda a, b, c=None: None))) - assert tstr.encode("utf-8") in ''.join(newapp({'HTTP_ACCEPT': + assert tstr.encode("utf-8") in b''.join(newapp({'HTTP_ACCEPT': 'text/plain'}, (lambda a, b, c=None: None))) @@ -67,15 +67,14 @@ def test_redapp(): raise HTTPFound("/bing/foo") app = HTTPExceptionHandler(redapp) result = list(app({'HTTP_ACCEPT': 'text/html'},saveit)) - assert '<a href="/bing/foo">' in result[0] + assert b'<a href="/bing/foo">' in result[0] assert "302 Found" == saved[0][0] - assert "text/html" == header_value(saved[0][1], 'content-type') + if six.PY3: + assert "text/html; charset=utf8" == header_value(saved[0][1], 'content-type') + else: + assert "text/html" == header_value(saved[0][1], 'content-type') assert "/bing/foo" == header_value(saved[0][1],'location') result = list(app({'HTTP_ACCEPT': 'text/plain'},saveit)) - print(result[0] == ( - '302 Found\n' - 'This resource was found at /bing/foo;\n' - 'you should be redirected automatically.\n')) assert "text/plain; charset=utf8" == header_value(saved[1][1],'content-type') assert "/bing/foo" == header_value(saved[1][1],'location') diff --git a/tests/test_fileapp.py b/tests/test_fileapp.py index d5b2a95..bdd7510 100644 --- a/tests/test_fileapp.py +++ b/tests/test_fileapp.py @@ -1,30 +1,38 @@ # (c) 2005 Ian Bicking, Clark C. Evans and contributors # This module is part of the Python Paste Project and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php -import string import time +import random +import os +import tempfile try: # Python 3 from email.utils import parsedate_tz, mktime_tz except ImportError: # Python 2 from rfc822 import parsedate_tz, mktime_tz +import six +from paste import fileapp from paste.fileapp import * from paste.fixture import * +# NOTE(haypo): don't use string.letters because the order of lower and upper +# case letters changes when locale.setlocale() is called for the first time +LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' + def test_data(): - harness = TestApp(DataApp('mycontent')) + harness = TestApp(DataApp(b'mycontent')) res = harness.get("/") assert 'application/octet-stream' == res.header('content-type') assert '9' == res.header('content-length') assert "<Response 200 OK 'mycontent'>" == repr(res) - harness.app.set_content("bingles") + harness.app.set_content(b"bingles") assert "<Response 200 OK 'bingles'>" == repr(harness.get("/")) def test_cache(): def build(*args,**kwargs): - app = DataApp("SomeContent") + app = DataApp(b"SomeContent") app.cache_control(*args,**kwargs) return TestApp(app).get("/") res = build() @@ -48,7 +56,7 @@ def test_cache(): def test_disposition(): def build(*args,**kwargs): - app = DataApp("SomeContent") + app = DataApp(b"SomeContent") app.content_disposition(*args,**kwargs) return TestApp(app).get("/") res = build() @@ -73,7 +81,7 @@ def test_disposition(): assert False, "should be an exception" def test_modified(): - harness = TestApp(DataApp('mycontent')) + harness = TestApp(DataApp(b'mycontent')) res = harness.get("/") assert "<Response 200 OK 'mycontent'>" == repr(res) last_modified = res.header('last-modified') @@ -84,21 +92,20 @@ def test_modified(): assert "<Response 304 Not Modified ''>" == repr(res) res = harness.get("/",status=400, headers={'if-modified-since': 'garbage'}) - assert 400 == res.status and "ill-formed timestamp" in res.body + assert 400 == res.status and b"ill-formed timestamp" in res.body res = harness.get("/",status=400, headers={'if-modified-since': 'Thu, 22 Dec 2030 01:01:01 GMT'}) - assert 400 == res.status and "check your system clock" in res.body + assert 400 == res.status and b"check your system clock" in res.body def test_file(): - import random, string, os tempfile = "test_fileapp.%s.txt" % (random.random()) - content = string.letters * 20 - file = open(tempfile,"w") - file.write(content) - file.close() + content = LETTERS * 20 + if six.PY3: + content = content.encode('utf8') + with open(tempfile, "wb") as fp: + fp.write(content) try: - from paste import fileapp app = fileapp.FileApp(tempfile) res = TestApp(app).get("/") assert len(content) == int(res.header('content-length')) @@ -113,7 +120,7 @@ def test_file(): res = TestApp(app).get("/",headers={'Cache-Control': 'max-age=0'}) assert len(content)+10 == int(res.header('content-length')) assert 'text/plain' == res.header('content-type') - assert content + "0123456789" == res.body + assert content + b"0123456789" == res.body assert app.content # we are still cached file = open(tempfile,"a+") file.write("X" * fileapp.CACHE_SIZE) # exceed the cashe size @@ -123,15 +130,12 @@ def test_file(): newsize = fileapp.CACHE_SIZE + len(content)+12 assert newsize == int(res.header('content-length')) assert newsize == len(res.body) - assert res.body.startswith(content) and res.body.endswith('XYZ') + assert res.body.startswith(content) and res.body.endswith(b'XYZ') assert not app.content # we are no longer cached finally: - import os os.unlink(tempfile) def test_dir(): - import os - import tempfile tmpdir = tempfile.mkdtemp() try: tmpfile = os.path.join(tmpdir, 'file') @@ -141,13 +145,12 @@ def test_dir(): fp.close() os.mkdir(tmpsubdir) try: - from paste import fileapp app = fileapp.DirectoryApp(tmpdir) for path in ['/', '', '//', '/..', '/.', '/../..']: assert TestApp(app).get(path, status=403).status == 403, ValueError(path) for path in ['/~', '/foo', '/dir', '/dir/']: assert TestApp(app).get(path, status=404).status == 404, ValueError(path) - assert TestApp(app).get('/file').body == 'abcd' + assert TestApp(app).get('/file').body == b'abcd' finally: os.remove(tmpfile) os.rmdir(tmpsubdir) @@ -171,44 +174,43 @@ def _excercize_range(build,content): assert res.body == content[:10] assert res.header('content-length') == '10' res = build("bytes=%d-" % (len(content)-1), status=206) - assert res.body == 'Z' + assert res.body == b'Z' assert res.header('content-length') == '1' res = build("bytes=%d-%d" % (3,17), status=206) assert res.body == content[3:18] assert res.header('content-length') == '15' def test_range(): - content = string.letters * 5 - def build(range, status=200): + content = LETTERS * 5 + if six.PY3: + content = content.encode('utf8') + def build(range, status=206): app = DataApp(content) return TestApp(app).get("/",headers={'Range': range}, status=status) _excercize_range(build,content) build('bytes=0-%d' % (len(content)+1), 416) def test_file_range(): - from paste import fileapp - import random, string, os tempfile = "test_fileapp.%s.txt" % (random.random()) - content = string.letters * (1+(fileapp.CACHE_SIZE / len(string.letters))) + content = LETTERS * (1+(fileapp.CACHE_SIZE // len(LETTERS))) + if six.PY3: + content = content.encode('utf8') assert len(content) > fileapp.CACHE_SIZE - file = open(tempfile,"w") - file.write(content) - file.close() + with open(tempfile, "wb") as fp: + fp.write(content) try: - def build(range, status=200): + def build(range, status=206): app = fileapp.FileApp(tempfile) return TestApp(app).get("/",headers={'Range': range}, status=status) _excercize_range(build,content) - for size in (13,len(string.letters),len(string.letters)-1): + for size in (13,len(LETTERS), len(LETTERS)-1): fileapp.BLOCK_SIZE = size _excercize_range(build,content) finally: - import os os.unlink(tempfile) def test_file_cache(): - from paste import fileapp filename = os.path.join(os.path.dirname(__file__), 'urlparser_data', 'secured.txt') app = TestApp(fileapp.FileApp(filename)) @@ -229,7 +231,6 @@ def test_file_cache(): status=400) def test_methods(): - from paste import fileapp filename = os.path.join(os.path.dirname(__file__), 'urlparser_data', 'secured.txt') app = TestApp(fileapp.FileApp(filename)) diff --git a/tests/test_grantip.py b/tests/test_grantip.py index 8d74280..2ddf7f1 100644 --- a/tests/test_grantip.py +++ b/tests/test_grantip.py @@ -4,11 +4,14 @@ from paste.fixture import * def test_make_app(): def application(environ, start_response): start_response('200 OK', [('content-type', 'text/plain')]) - return [ + lines = [ str(environ.get('REMOTE_USER')), ':', str(environ.get('REMOTE_USER_TOKENS')), ] + if six.PY3: + lines = [line.encode('utf8') for line in lines] + return lines ip_map = { '127.0.0.1': (None, 'system'), '192.168.0.0/16': (None, 'worker'), @@ -24,11 +27,11 @@ def test_req(): def doit(remote_addr): res = app.get('/', extra_environ={'REMOTE_ADDR': remote_addr}) return res.body - assert doit('127.0.0.1') == 'None:system' - assert doit('192.168.15.12') == 'None:worker' - assert doit('192.168.0.4') == 'None:worker' + assert doit('127.0.0.1') == b'None:system' + assert doit('192.168.15.12') == b'None:worker' + assert doit('192.168.0.4') == b'None:worker' result = doit('192.168.0.5') - assert result.startswith('bob:') - assert 'editor' in result and 'worker' in result - assert result.count(',') == 1 - assert doit('192.168.0.8') == 'None:editor' + assert result.startswith(b'bob:') + assert b'editor' in result and b'worker' in result + assert result.count(b',') == 1 + assert doit('192.168.0.8') == b'None:editor' diff --git a/tests/test_gzipper.py b/tests/test_gzipper.py index 4f929b0..54b7901 100644 --- a/tests/test_gzipper.py +++ b/tests/test_gzipper.py @@ -1,11 +1,11 @@ from paste.fixture import TestApp from paste.gzipper import middleware import gzip -from six.moves import cStringIO as StringIO +import six def simple_app(environ, start_response): start_response('200 OK', [('content-type', 'text/plain')]) - return 'this is a test' + return [b'this is a test'] wsgi_app = middleware(simple_app) app = TestApp(wsgi_app) @@ -14,6 +14,6 @@ def test_gzip(): res = app.get( '/', extra_environ=dict(HTTP_ACCEPT_ENCODING='gzip')) assert int(res.header('content-length')) == len(res.body) - assert res.body != 'this is a test' - actual = gzip.GzipFile(fileobj=StringIO(res.body)).read() - assert actual == 'this is a test' + assert res.body != b'this is a test' + actual = gzip.GzipFile(fileobj=six.BytesIO(res.body)).read() + assert actual == b'this is a test' diff --git a/tests/test_import_string.py b/tests/test_import_string.py index 96526ac..262cbdd 100644 --- a/tests/test_import_string.py +++ b/tests/test_import_string.py @@ -11,6 +11,6 @@ def test_simple(): def test_complex(): assert eval_import('sys:version') is sys.version assert eval_import('os:getcwd()') == os.getcwd() - assert (eval_import('sys:version.split()[0]') == + assert (eval_import('sys:version.split()[0]') == sys.version.split()[0]) - + diff --git a/tests/test_multidict.py b/tests/test_multidict.py index 820331e..50a746f 100644 --- a/tests/test_multidict.py +++ b/tests/test_multidict.py @@ -7,8 +7,6 @@ from six.moves import StringIO from nose.tools import assert_raises -from paste.fixture import TestApp -from paste.wsgiwrappers import WSGIRequest from paste.util.multidict import MultiDict, UnicodeMultiDict def test_dict(): @@ -59,15 +57,17 @@ def test_unicode_dict(): _test_unicode_dict(decode_param_names=True) def _test_unicode_dict(decode_param_names=False): - d = UnicodeMultiDict(MultiDict({'a': 'a test'})) + d = UnicodeMultiDict(MultiDict({b'a': 'a test'})) d.encoding = 'utf-8' d.errors = 'ignore' if decode_param_names: key_str = six.text_type + k = lambda key: key d.decode_keys = True else: - key_str = str + key_str = six.binary_type + k = lambda key: key.encode() def assert_unicode(obj): assert isinstance(obj, six.text_type) @@ -80,67 +80,67 @@ def _test_unicode_dict(decode_param_names=False): assert isinstance(key, key_str) assert isinstance(value, six.text_type) - assert d.items() == [('a', u'a test')] + assert d.items() == [(k('a'), u'a test')] map(assert_key_str, d.keys()) map(assert_unicode, d.values()) - d['b'] = '2 test' - d['c'] = '3 test' - assert d.items() == [('a', u'a test'), ('b', u'2 test'), ('c', u'3 test')] - map(assert_unicode_item, d.items()) + d[b'b'] = b'2 test' + d[b'c'] = b'3 test' + assert d.items() == [(k('a'), u'a test'), (k('b'), u'2 test'), (k('c'), u'3 test')] + list(map(assert_unicode_item, d.items())) - d['b'] = '4 test' - assert d.items() == [('a', u'a test'), ('c', u'3 test'), ('b', u'4 test')] - map(assert_unicode_item, d.items()) + d[k('b')] = b'4 test' + assert d.items() == [(k('a'), u'a test'), (k('c'), u'3 test'), (k('b'), u'4 test')], d.items() + list(map(assert_unicode_item, d.items())) - d.add('b', '5 test') - assert_raises(KeyError, d.getone, "b") - assert d.getall('b') == [u'4 test', u'5 test'] + d.add(k('b'), b'5 test') + assert_raises(KeyError, d.getone, k("b")) + assert d.getall(k('b')) == [u'4 test', u'5 test'] map(assert_unicode, d.getall('b')) - assert d.items() == [('a', u'a test'), ('c', u'3 test'), ('b', u'4 test'), - ('b', u'5 test')] - map(assert_unicode_item, d.items()) + assert d.items() == [(k('a'), u'a test'), (k('c'), u'3 test'), (k('b'), u'4 test'), + (k('b'), u'5 test')] + list(map(assert_unicode_item, d.items())) - del d['b'] - assert d.items() == [('a', u'a test'), ('c', u'3 test')] - map(assert_unicode_item, d.items()) + del d[k('b')] + assert d.items() == [(k('a'), u'a test'), (k('c'), u'3 test')] + list(map(assert_unicode_item, d.items())) assert d.pop('xxx', u'5 test') == u'5 test' assert isinstance(d.pop('xxx', u'5 test'), six.text_type) - assert d.getone('a') == u'a test' - assert isinstance(d.getone('a'), six.text_type) - assert d.popitem() == ('c', u'3 test') - d['c'] = '3 test' + assert d.getone(k('a')) == u'a test' + assert isinstance(d.getone(k('a')), six.text_type) + assert d.popitem() == (k('c'), u'3 test') + d[k('c')] = b'3 test' assert_unicode_item(d.popitem()) - assert d.items() == [('a', u'a test')] - map(assert_unicode_item, d.items()) + assert d.items() == [(k('a'), u'a test')] + list(map(assert_unicode_item, d.items())) item = [] - assert d.setdefault('z', item) is item + assert d.setdefault(k('z'), item) is item items = d.items() - assert items == [('a', u'a test'), ('z', item)] + assert items == [(k('a'), u'a test'), (k('z'), item)] assert isinstance(items[1][0], key_str) assert isinstance(items[1][1], list) - assert isinstance(d.setdefault('y', 'y test'), six.text_type) - assert isinstance(d['y'], six.text_type) + assert isinstance(d.setdefault(k('y'), b'y test'), six.text_type) + assert isinstance(d[k('y')], six.text_type) - assert d.mixed() == {u'a': u'a test', u'y': u'y test', u'z': item} - assert d.dict_of_lists() == {u'a': [u'a test'], u'y': [u'y test'], - u'z': [item]} - del d['z'] - map(assert_unicode_item, six.iteritems(d.mixed())) - map(assert_unicode_item, [(k, v[0]) for \ - k, v in six.iteritems(d.dict_of_lists())]) + assert d.mixed() == {k('a'): u'a test', k('y'): u'y test', k('z'): item} + assert d.dict_of_lists() == {k('a'): [u'a test'], k('y'): [u'y test'], + k('z'): [item]} + del d[k('z')] + list(map(assert_unicode_item, six.iteritems(d.mixed()))) + list(map(assert_unicode_item, [(key, value[0]) for \ + key, value in six.iteritems(d.dict_of_lists())])) - assert u'a' in d + assert k('a') in d dcopy = d.copy() assert dcopy is not d assert dcopy == d - d['x'] = 'x test' + d[k('x')] = 'x test' assert dcopy != d d[(1, None)] = (None, 1) - assert d.items() == [('a', u'a test'), ('y', u'y test'), ('x', u'x test'), + assert d.items() == [(k('a'), u'a test'), (k('y'), u'y test'), (k('x'), u'x test'), ((1, None), (None, 1))] item = d.items()[-1] assert isinstance(item[0], tuple) @@ -150,12 +150,12 @@ def _test_unicode_dict(decode_param_names=False): fs.name = 'thefile' fs.filename = 'hello.txt' fs.file = StringIO('hello') - d['f'] = fs - ufs = d['f'] + d[k('f')] = fs + ufs = d[k('f')] assert isinstance(ufs, cgi.FieldStorage) assert ufs is not fs assert ufs.name == fs.name - assert isinstance(ufs.name, key_str) + assert isinstance(ufs.name, str if six.PY3 else key_str) assert ufs.filename == fs.filename assert isinstance(ufs.filename, six.text_type) assert isinstance(ufs.value, str) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 36d16b5..44db9f3 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -9,4 +9,4 @@ def test_paste_website(): app = TestApp(app) res = app.get('/') assert 'documentation' in res - + diff --git a/tests/test_recursive.py b/tests/test_recursive.py index 114592e..1cb1984 100644 --- a/tests/test_recursive.py +++ b/tests/test_recursive.py @@ -1,14 +1,14 @@ -from .test_errordocument import error_docs_app, test_error_docs_app, simple_app +from .test_errordocument import simple_app from paste.fixture import * from paste.recursive import RecursiveMiddleware, ForwardRequestException def error_docs_app(environ, start_response): if environ['PATH_INFO'] == '/not_found': start_response("404 Not found", [('Content-type', 'text/plain')]) - return ['Not found'] + return [b'Not found'] elif environ['PATH_INFO'] == '/error': start_response("200 OK", [('Content-type', 'text/plain')]) - return ['Page not found'] + return [b'Page not found'] elif environ['PATH_INFO'] == '/recurse': raise ForwardRequestException('/recurse') else: @@ -43,15 +43,15 @@ def forward(app): else: raise AssertionError('Failed to detect forwarding loop') -def test_ForwardRequest_url(): +def test_ForwardRequest_url(): class TestForwardRequestMiddleware(Middleware): def __call__(self, environ, start_response): if environ['PATH_INFO'] != '/not_found': return self.app(environ, start_response) raise ForwardRequestException(self.url) forward(TestForwardRequestMiddleware(error_docs_app)) - -def test_ForwardRequest_environ(): + +def test_ForwardRequest_environ(): class TestForwardRequestMiddleware(Middleware): def __call__(self, environ, start_response): if environ['PATH_INFO'] != '/not_found': @@ -59,11 +59,11 @@ def test_ForwardRequest_environ(): environ['PATH_INFO'] = self.url raise ForwardRequestException(environ=environ) forward(TestForwardRequestMiddleware(error_docs_app)) - -def test_ForwardRequest_factory(): - + +def test_ForwardRequest_factory(): + from paste.errordocument import StatusKeeper - + class TestForwardRequestMiddleware(Middleware): def __call__(self, environ, start_response): if environ['PATH_INFO'] != '/not_found': @@ -96,7 +96,7 @@ def test_ForwardRequest_factory(): raise AssertionError('Failed to detect forwarding loop') # Test Deprecated Code -def test_ForwardRequestException(): +def test_ForwardRequestException(): class TestForwardRequestExceptionMiddleware(Middleware): def __call__(self, environ, start_response): if environ['PATH_INFO'] != '/not_found': diff --git a/tests/test_registry.py b/tests/test_registry.py index fdbc26c..23cd9b6 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -15,19 +15,25 @@ def simpleapp(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) - return ['Hello world!\n'] + return [b'Hello world!\n'] def simpleapp_withregistry(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) - return ['Hello world!Value is %s\n' % regobj.keys()] + body = 'Hello world!Value is %s\n' % regobj.keys() + if six.PY3: + body = body.encode('utf8') + return [body] def simpleapp_withregistry_default(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) - return ['Hello world!Value is %s\n' % secondobj] + body = 'Hello world!Value is %s\n' % secondobj + if six.PY3: + body = body.encode('utf8') + return [body] class RegistryUsingApp(object): @@ -35,7 +41,7 @@ class RegistryUsingApp(object): self.var = var self.value = value self.raise_exc = raise_exc - + def __call__(self, environ, start_response): if 'paste.registry' in environ: environ['paste.registry'].register(self.var, self.value) @@ -44,20 +50,26 @@ class RegistryUsingApp(object): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) - return ['Hello world!\nThe variable is %s' % str(regobj)] + body = 'Hello world!\nThe variable is %s' % str(regobj) + if six.PY3: + body = body.encode('utf8') + return [body] class RegistryUsingIteratorApp(object): def __init__(self, var, value): self.var = var self.value = value - + def __call__(self, environ, start_response): if 'paste.registry' in environ: environ['paste.registry'].register(self.var, self.value) status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) - return iter(['Hello world!\nThe variable is %s' % str(regobj)]) + body = 'Hello world!\nThe variable is %s' % str(regobj) + if six.PY3: + body = body.encode('utf8') + return iter([body]) class RegistryMiddleMan(object): def __init__(self, app, var, value, depth): @@ -65,12 +77,15 @@ class RegistryMiddleMan(object): self.var = var self.value = value self.depth = depth - + def __call__(self, environ, start_response): if 'paste.registry' in environ: environ['paste.registry'].register(self.var, self.value) - app_response = ['\nInserted by middleware!\nInsertValue at depth \ - %s is %s' % (self.depth, str(regobj))] + line = ('\nInserted by middleware!\nInsertValue at depth %s is %s' + % (self.depth, str(regobj))) + if six.PY3: + line = line.encode('utf8') + app_response = [line] app_iter = None app_iter = self.app(environ, start_response) if type(app_iter) in (list, tuple): @@ -82,10 +97,13 @@ class RegistryMiddleMan(object): if hasattr(app_iter, 'close'): app_iter.close() app_response.extend(response) - app_response.extend(['\nAppended by middleware!\nAppendValue at \ - depth %s is %s' % (self.depth, str(regobj))]) + line = ('\nAppended by middleware!\nAppendValue at \ + depth %s is %s' % (self.depth, str(regobj))) + if six.PY3: + line = line.encode('utf8') + app_response.append(line) return app_response - + def test_simple(): app = TestApp(simpleapp) @@ -150,7 +168,7 @@ def test_really_deep_registry(): for depth in valuelist: assert "AppendValue at depth %s is {'%s': %s}" % \ (depth, keylist[depth], depth) in res - + def test_iterating_response(): obj = {'hi':'people'} secondobj = {'bye':'friends'} diff --git a/tests/test_request.py b/tests/test_request.py index 3d882ed..072304d 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -4,24 +4,28 @@ from paste.fixture import * from paste.request import * from paste.wsgiwrappers import WSGIRequest +import six def simpleapp(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) request = WSGIRequest(environ) - return [ + body = [ 'Hello world!\n', 'The get is %s' % str(request.GET), ' and Val is %s\n' % request.GET.get('name'), 'The languages are: %s\n' % request.languages, 'The accepttypes is: %s\n' % request.match_accept(['text/html', 'application/xml'])] + if six.PY3: + body = [line.encode('utf8') for line in body] + return body def test_gets(): app = TestApp(simpleapp) res = app.get('/') assert 'Hello' in res assert "get is MultiDict([])" in res - + res = app.get('/?name=george') res.mustcontain("get is MultiDict([('name', 'george')])") res.mustcontain("Val is george") @@ -30,7 +34,7 @@ def test_language_parsing(): app = TestApp(simpleapp) res = app.get('/') assert "The languages are: ['en-us']" in res - + res = app.get('/', headers={'Accept-Language':'da, en-gb;q=0.8, en;q=0.7'}) assert "languages are: ['da', 'en-gb', 'en', 'en-us']" in res @@ -41,10 +45,10 @@ def test_mime_parsing(): app = TestApp(simpleapp) res = app.get('/', headers={'Accept':'text/html'}) assert "accepttypes is: ['text/html']" in res - + res = app.get('/', headers={'Accept':'application/xml'}) assert "accepttypes is: ['application/xml']" in res - + res = app.get('/', headers={'Accept':'application/xml,*/*'}) assert "accepttypes is: ['text/html', 'application/xml']" in res diff --git a/tests/test_request_form.py b/tests/test_request_form.py index 036da3e..cf43721 100644 --- a/tests/test_request_form.py +++ b/tests/test_request_form.py @@ -1,5 +1,4 @@ -import cgi -from six.moves import cStringIO as StringIO +import six from paste.request import * from paste.util.multidict import MultiDict @@ -19,13 +18,13 @@ def make_post(body): 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': str(len(body)), 'REQUEST_METHOD': 'POST', - 'wsgi.input': StringIO(body), + 'wsgi.input': six.BytesIO(body), } return e def test_parsevars(): - e = make_post('a=1&b=2&c=3&b=4') - cur_input = e['wsgi.input'] + e = make_post(b'a=1&b=2&c=3&b=4') + #cur_input = e['wsgi.input'] d = parse_formvars(e) assert isinstance(d, MultiDict) assert d == MultiDict([('a', '1'), ('b', '2'), ('c', '3'), ('b', '4')]) diff --git a/tests/test_response.py b/tests/test_response.py index d4d4b65..71f6f97 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -8,4 +8,4 @@ def test_replace_header(): replace_header(h, 'Content-Type', 'text/html') assert ('content-type', 'text/html') in h assert ('content-type', 'text/plain') not in h - + diff --git a/tests/test_session.py b/tests/test_session.py index 621d284..b67bda5 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1,5 +1,6 @@ from paste.session import SessionMiddleware from paste.fixture import TestApp +import six info = [] @@ -12,9 +13,12 @@ def wsgi_app(environ, start_response): if pi == '/get2': sess = environ['paste.session.factory']() if 'info' in sess: - return [str(sess['info'])] + body = str(sess['info']) + if six.PY3: + body = body.encode('utf8') + return [body] else: - return ['no-info'] + return [b'no-info'] if pi in ('/put1', '/put2'): if pi == '/put1': sess = environ['paste.session.factory']() @@ -23,30 +27,30 @@ def wsgi_app(environ, start_response): if pi == '/put2': sess = environ['paste.session.factory']() sess['info'] = info[0] - return ['foo'] + return [b'foo'] wsgi_app = SessionMiddleware(wsgi_app) - + def test_app1(): app = TestApp(wsgi_app) res = app.get('/get1') - assert res.body == 'no-info' + assert res.body == b'no-info' res = app.get('/get2') - assert res.body == 'no-info' + assert res.body ==b'no-info' info[:] = ['test'] res = app.get('/put1') res = app.get('/get1') - assert res.body == 'test' + assert res.body == b'test' res = app.get('/get2') - assert res.body == 'test' + assert res.body == b'test' def test_app2(): app = TestApp(wsgi_app) info[:] = ['fluff'] res = app.get('/put2') res = app.get('/get1') - assert res.body == 'fluff' + assert res.body == b'fluff' res = app.get('/get2') - assert res.body == 'fluff' - - + assert res.body == b'fluff' + + diff --git a/tests/test_urlmap.py b/tests/test_urlmap.py index 9f77ca2..f7ec729 100644 --- a/tests/test_urlmap.py +++ b/tests/test_urlmap.py @@ -1,11 +1,15 @@ from paste.urlmap import * from paste.fixture import * +import six def make_app(response_text): def app(environ, start_response): headers = [('Content-type', 'text/html')] start_response('200 OK', headers) - return [response_text % environ] + body = response_text % environ + if six.PY3: + body = body.encode('ascii') + return [body] return app def test_map(): @@ -44,6 +48,6 @@ def test_404(): mapper = URLMap({}) app = TestApp(mapper, extra_environ={'HTTP_ACCEPT': 'text/html'}) res = app.get("/-->%0D<script>alert('xss')</script>", status=404) - assert '--><script' not in res.body + assert b'--><script' not in res.body res = app.get("/--%01><script>", status=404) - assert '--\x01><script>' not in res.body + assert b'--\x01><script>' not in res.body diff --git a/tests/test_urlparser.py b/tests/test_urlparser.py index d1f3377..21c210e 100644 --- a/tests/test_urlparser.py +++ b/tests/test_urlparser.py @@ -110,7 +110,7 @@ def test_xss(): app = TestApp(StaticURLParser(relative_path('find_file')), extra_environ={'HTTP_ACCEPT': 'text/html'}) res = app.get("/-->%0D<script>alert('xss')</script>", status=404) - assert '--><script>' not in res.body + assert b'--><script>' not in res.body def test_static_parser(): app = StaticURLParser(path('find_file')) @@ -118,16 +118,16 @@ def test_static_parser(): res = testapp.get('', status=301) res = testapp.get('/', status=404) res = testapp.get('/index.txt') - assert res.body.strip() == 'index1' + assert res.body.strip() == b'index1' res = testapp.get('/index.txt/foo', status=404) res = testapp.get('/test 3.html') - assert res.body.strip() == 'test 3' + assert res.body.strip() == b'test 3' res = testapp.get('/test%203.html') - assert res.body.strip() == 'test 3' + assert res.body.strip() == b'test 3' res = testapp.get('/dir with spaces/test 4.html') - assert res.body.strip() == 'test 4' + assert res.body.strip() == b'test 4' res = testapp.get('/dir%20with%20spaces/test%204.html') - assert res.body.strip() == 'test 4' + assert res.body.strip() == b'test 4' # Ensure only data under the app's root directory is accessible res = testapp.get('/../secured.txt', status=404) res = testapp.get('/dir with spaces/../../secured.txt', status=404) diff --git a/tests/test_util/test_datetimeutil.py b/tests/test_util/test_datetimeutil.py index 17808f3..45d96c7 100644 --- a/tests/test_util/test_datetimeutil.py +++ b/tests/test_util/test_datetimeutil.py @@ -1,135 +1,135 @@ -# (c) 2005 Clark C. Evans and contributors
-# This module is part of the Python Paste Project and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-# Some of this code was funded by: http://prometheusresearch.com
-from time import localtime
-from datetime import date
-from paste.util.datetimeutil import *
-
-def test_timedelta():
- assert('' == normalize_timedelta(""))
- assert('0.10' == normalize_timedelta("6m"))
- assert('0.50' == normalize_timedelta("30m"))
- assert('0.75' == normalize_timedelta("45m"))
- assert('1.00' == normalize_timedelta("60 min"))
- assert('1.50' == normalize_timedelta("90min"))
- assert('1.50' == normalize_timedelta("1.50"))
- assert('4.50' == normalize_timedelta("4 : 30"))
- assert('1.50' == normalize_timedelta("1h 30m"))
- assert('1.00' == normalize_timedelta("1"))
- assert('1.00' == normalize_timedelta("1 hour"))
- assert('8.00' == normalize_timedelta("480 mins"))
- assert('8.00' == normalize_timedelta("8h"))
- assert('0.50' == normalize_timedelta("0.5"))
- assert('0.10' == normalize_timedelta(".1"))
- assert('0.50' == normalize_timedelta(".50"))
- assert('0.75' == normalize_timedelta("0.75"))
-
-def test_time():
- assert('03:00 PM' == normalize_time("3p", ampm=True))
- assert('03:00 AM' == normalize_time("300", ampm=True))
- assert('03:22 AM' == normalize_time("322", ampm=True))
- assert('01:22 PM' == normalize_time("1322", ampm=True))
- assert('01:00 PM' == normalize_time("13", ampm=True))
- assert('12:00 PM' == normalize_time("noon", ampm=True))
- assert("06:00 PM" == normalize_time("6", ampm=True))
- assert("01:00 PM" == normalize_time("1", ampm=True))
- assert("07:00 AM" == normalize_time("7", ampm=True))
- assert("01:00 PM" == normalize_time("1 pm", ampm=True))
- assert("03:30 PM" == normalize_time("3:30 pm", ampm=True))
- assert("03:30 PM" == normalize_time("3 30 pm", ampm=True))
- assert("03:30 PM" == normalize_time("3 30 P.M.", ampm=True))
- assert("12:00 PM" == normalize_time("0", ampm=True))
- assert("12:00 AM" == normalize_time("1200 AM", ampm=True))
-
-def test_date():
- tm = localtime()
- yr = tm[0]
- mo = tm[1]
- assert(date(yr,4,11) == parse_date("411"))
- assert(date(yr,4,11) == parse_date("APR11"))
- assert(date(yr,4,11) == parse_date("11APR"))
- assert(date(yr,4,11) == parse_date("4 11"))
- assert(date(yr,4,11) == parse_date("11 APR"))
- assert(date(yr,4,11) == parse_date("APR 11"))
- assert(date(yr,mo,11) == parse_date("11"))
- assert(date(yr,4,1) == parse_date("APR"))
- assert(date(yr,4,11) == parse_date("4/11"))
- assert(date.today() == parse_date("today"))
- assert(date.today() == parse_date("now"))
- assert(None == parse_date(""))
- assert('' == normalize_date(None))
-
- assert('2001-02-03' == normalize_date("20010203"))
- assert('1999-04-11' == normalize_date("1999 4 11"))
- assert('1999-04-11' == normalize_date("1999 APR 11"))
- assert('1999-04-11' == normalize_date("APR 11 1999"))
- assert('1999-04-11' == normalize_date("11 APR 1999"))
- assert('1999-04-11' == normalize_date("4 11 1999"))
- assert('1999-04-01' == normalize_date("1999 APR"))
- assert('1999-04-01' == normalize_date("1999 4"))
- assert('1999-04-01' == normalize_date("4 1999"))
- assert('1999-04-01' == normalize_date("APR 1999"))
- assert('1999-01-01' == normalize_date("1999"))
-
- assert('1999-04-01' == normalize_date("1APR1999"))
- assert('2001-04-01' == normalize_date("1APR2001"))
-
- assert('1999-04-18' == normalize_date("1999-04-11+7"))
- assert('1999-04-18' == normalize_date("1999-04-11 7"))
- assert('1999-04-01' == normalize_date("1 apr 1999"))
- assert('1999-04-11' == normalize_date("11 apr 1999"))
- assert('1999-04-11' == normalize_date("11 Apr 1999"))
- assert('1999-04-11' == normalize_date("11-apr-1999"))
- assert('1999-04-11' == normalize_date("11 April 1999"))
- assert('1999-04-11' == normalize_date("11 APRIL 1999"))
- assert('1999-04-11' == normalize_date("11 april 1999"))
- assert('1999-04-11' == normalize_date("11 aprick 1999"))
- assert('1999-04-11' == normalize_date("APR 11, 1999"))
- assert('1999-04-11' == normalize_date("4/11/1999"))
- assert('1999-04-11' == normalize_date("4-11-1999"))
- assert('1999-04-11' == normalize_date("1999-4-11"))
- assert('1999-04-11' == normalize_date("19990411"))
-
- assert('1999-01-01' == normalize_date("1 Jan 1999"))
- assert('1999-02-01' == normalize_date("1 Feb 1999"))
- assert('1999-03-01' == normalize_date("1 Mar 1999"))
- assert('1999-04-01' == normalize_date("1 Apr 1999"))
- assert('1999-05-01' == normalize_date("1 May 1999"))
- assert('1999-06-01' == normalize_date("1 Jun 1999"))
- assert('1999-07-01' == normalize_date("1 Jul 1999"))
- assert('1999-08-01' == normalize_date("1 Aug 1999"))
- assert('1999-09-01' == normalize_date("1 Sep 1999"))
- assert('1999-10-01' == normalize_date("1 Oct 1999"))
- assert('1999-11-01' == normalize_date("1 Nov 1999"))
- assert('1999-12-01' == normalize_date("1 Dec 1999"))
-
- assert('1999-04-30' == normalize_date("1999-4-30"))
- assert('2000-02-29' == normalize_date("29 FEB 2000"))
- assert('2001-02-28' == normalize_date("28 FEB 2001"))
- assert('2004-02-29' == normalize_date("29 FEB 2004"))
- assert('2100-02-28' == normalize_date("28 FEB 2100"))
- assert('1900-02-28' == normalize_date("28 FEB 1900"))
-
- def assertError(val):
- try:
- normalize_date(val)
- except (TypeError,ValueError):
- return
- raise ValueError("type error expected", val)
-
- assertError("2000-13-11")
- assertError("APR 99")
- assertError("29 FEB 1900")
- assertError("29 FEB 2100")
- assertError("29 FEB 2001")
- assertError("1999-4-31")
- assertError("APR 99")
- assertError("20301")
- assertError("020301")
- assertError("1APR99")
- assertError("1APR01")
- assertError("1 APR 99")
- assertError("1 APR 01")
- assertError("11/5/01")
-
+# (c) 2005 Clark C. Evans and contributors +# This module is part of the Python Paste Project and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php +# Some of this code was funded by: http://prometheusresearch.com +from time import localtime +from datetime import date +from paste.util.datetimeutil import * + +def test_timedelta(): + assert('' == normalize_timedelta("")) + assert('0.10' == normalize_timedelta("6m")) + assert('0.50' == normalize_timedelta("30m")) + assert('0.75' == normalize_timedelta("45m")) + assert('1.00' == normalize_timedelta("60 min")) + assert('1.50' == normalize_timedelta("90min")) + assert('1.50' == normalize_timedelta("1.50")) + assert('4.50' == normalize_timedelta("4 : 30")) + assert('1.50' == normalize_timedelta("1h 30m")) + assert('1.00' == normalize_timedelta("1")) + assert('1.00' == normalize_timedelta("1 hour")) + assert('8.00' == normalize_timedelta("480 mins")) + assert('8.00' == normalize_timedelta("8h")) + assert('0.50' == normalize_timedelta("0.5")) + assert('0.10' == normalize_timedelta(".1")) + assert('0.50' == normalize_timedelta(".50")) + assert('0.75' == normalize_timedelta("0.75")) + +def test_time(): + assert('03:00 PM' == normalize_time("3p", ampm=True)) + assert('03:00 AM' == normalize_time("300", ampm=True)) + assert('03:22 AM' == normalize_time("322", ampm=True)) + assert('01:22 PM' == normalize_time("1322", ampm=True)) + assert('01:00 PM' == normalize_time("13", ampm=True)) + assert('12:00 PM' == normalize_time("noon", ampm=True)) + assert("06:00 PM" == normalize_time("6", ampm=True)) + assert("01:00 PM" == normalize_time("1", ampm=True)) + assert("07:00 AM" == normalize_time("7", ampm=True)) + assert("01:00 PM" == normalize_time("1 pm", ampm=True)) + assert("03:30 PM" == normalize_time("3:30 pm", ampm=True)) + assert("03:30 PM" == normalize_time("3 30 pm", ampm=True)) + assert("03:30 PM" == normalize_time("3 30 P.M.", ampm=True)) + assert("12:00 PM" == normalize_time("0", ampm=True)) + assert("12:00 AM" == normalize_time("1200 AM", ampm=True)) + +def test_date(): + tm = localtime() + yr = tm[0] + mo = tm[1] + assert(date(yr,4,11) == parse_date("411")) + assert(date(yr,4,11) == parse_date("APR11")) + assert(date(yr,4,11) == parse_date("11APR")) + assert(date(yr,4,11) == parse_date("4 11")) + assert(date(yr,4,11) == parse_date("11 APR")) + assert(date(yr,4,11) == parse_date("APR 11")) + assert(date(yr,mo,11) == parse_date("11")) + assert(date(yr,4,1) == parse_date("APR")) + assert(date(yr,4,11) == parse_date("4/11")) + assert(date.today() == parse_date("today")) + assert(date.today() == parse_date("now")) + assert(None == parse_date("")) + assert('' == normalize_date(None)) + + assert('2001-02-03' == normalize_date("20010203")) + assert('1999-04-11' == normalize_date("1999 4 11")) + assert('1999-04-11' == normalize_date("1999 APR 11")) + assert('1999-04-11' == normalize_date("APR 11 1999")) + assert('1999-04-11' == normalize_date("11 APR 1999")) + assert('1999-04-11' == normalize_date("4 11 1999")) + assert('1999-04-01' == normalize_date("1999 APR")) + assert('1999-04-01' == normalize_date("1999 4")) + assert('1999-04-01' == normalize_date("4 1999")) + assert('1999-04-01' == normalize_date("APR 1999")) + assert('1999-01-01' == normalize_date("1999")) + + assert('1999-04-01' == normalize_date("1APR1999")) + assert('2001-04-01' == normalize_date("1APR2001")) + + assert('1999-04-18' == normalize_date("1999-04-11+7")) + assert('1999-04-18' == normalize_date("1999-04-11 7")) + assert('1999-04-01' == normalize_date("1 apr 1999")) + assert('1999-04-11' == normalize_date("11 apr 1999")) + assert('1999-04-11' == normalize_date("11 Apr 1999")) + assert('1999-04-11' == normalize_date("11-apr-1999")) + assert('1999-04-11' == normalize_date("11 April 1999")) + assert('1999-04-11' == normalize_date("11 APRIL 1999")) + assert('1999-04-11' == normalize_date("11 april 1999")) + assert('1999-04-11' == normalize_date("11 aprick 1999")) + assert('1999-04-11' == normalize_date("APR 11, 1999")) + assert('1999-04-11' == normalize_date("4/11/1999")) + assert('1999-04-11' == normalize_date("4-11-1999")) + assert('1999-04-11' == normalize_date("1999-4-11")) + assert('1999-04-11' == normalize_date("19990411")) + + assert('1999-01-01' == normalize_date("1 Jan 1999")) + assert('1999-02-01' == normalize_date("1 Feb 1999")) + assert('1999-03-01' == normalize_date("1 Mar 1999")) + assert('1999-04-01' == normalize_date("1 Apr 1999")) + assert('1999-05-01' == normalize_date("1 May 1999")) + assert('1999-06-01' == normalize_date("1 Jun 1999")) + assert('1999-07-01' == normalize_date("1 Jul 1999")) + assert('1999-08-01' == normalize_date("1 Aug 1999")) + assert('1999-09-01' == normalize_date("1 Sep 1999")) + assert('1999-10-01' == normalize_date("1 Oct 1999")) + assert('1999-11-01' == normalize_date("1 Nov 1999")) + assert('1999-12-01' == normalize_date("1 Dec 1999")) + + assert('1999-04-30' == normalize_date("1999-4-30")) + assert('2000-02-29' == normalize_date("29 FEB 2000")) + assert('2001-02-28' == normalize_date("28 FEB 2001")) + assert('2004-02-29' == normalize_date("29 FEB 2004")) + assert('2100-02-28' == normalize_date("28 FEB 2100")) + assert('1900-02-28' == normalize_date("28 FEB 1900")) + + def assertError(val): + try: + normalize_date(val) + except (TypeError,ValueError): + return + raise ValueError("type error expected", val) + + assertError("2000-13-11") + assertError("APR 99") + assertError("29 FEB 1900") + assertError("29 FEB 2100") + assertError("29 FEB 2001") + assertError("1999-4-31") + assertError("APR 99") + assertError("20301") + assertError("020301") + assertError("1APR99") + assertError("1APR01") + assertError("1 APR 99") + assertError("1 APR 01") + assertError("11/5/01") + diff --git a/tests/test_util/test_mimeparse.py b/tests/test_util/test_mimeparse.py index c2d6cdf..9b9b675 100644 --- a/tests/test_util/test_mimeparse.py +++ b/tests/test_util/test_mimeparse.py @@ -1,237 +1,235 @@ -# (c) 2010 Ch. Zwerschke and contributors
-# This module is part of the Python Paste Project and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from time import localtime
-from datetime import date
-from paste.util.mimeparse import *
-
-def test_parse_mime_type():
- parse = parse_mime_type
- assert parse('*/*') == ('*', '*', {})
- assert parse('text/html') == ('text', 'html', {})
- assert parse('audio/*; q=0.2') == ('audio', '*', {'q': '0.2'})
- assert parse('text/x-dvi;level=1') == ('text', 'x-dvi', {'level': '1'})
- assert parse('image/gif; level=2; q=0.4') == (
- 'image', 'gif', {'level': '2', 'q': '0.4'})
- assert parse('application/xhtml;level=3;q=0.5') == (
- 'application', 'xhtml', {'level': '3', 'q': '0.5'})
- assert parse('application/xml') == ('application', 'xml', {})
- assert parse('application/xml;q=1') == ('application', 'xml', {'q': '1'})
- assert parse('application/xml ; q=1;b=other') == (
- 'application', 'xml', {'q': '1', 'b': 'other'})
- assert parse('application/xml ; q=2;b=other') == (
- 'application', 'xml', {'q': '2', 'b': 'other'})
- assert parse('application/xhtml;q=0.5') == (
- 'application', 'xhtml', {'q': '0.5'})
- assert parse('application/xhtml;q=0.5;ver=1.2') == (
- 'application', 'xhtml', {'q': '0.5', 'ver': '1.2'})
-
-def test_parse_illformed_mime_type():
- parse = parse_mime_type
- assert parse('*') == ('*', '*', {})
- assert parse('text') == ('text', '*', {})
- assert parse('text/') == ('text', '*', {})
- assert parse('/plain') == ('*', 'plain', {})
- assert parse('/') == ('*', '*', {})
- assert parse('text/plain;') == ('text', 'plain', {})
- assert parse(';q=0.5') == ('*', '*', {'q': '0.5'})
- assert parse('*; q=.2') == ('*', '*', {'q': '.2'})
- assert parse('image; q=.7; level=3') == (
- 'image', '*', {'q': '.7', 'level': '3'})
- assert parse('*;q=1') == ('*', '*', {'q': '1'})
- assert parse('*;q=') == ('*', '*', {})
- assert parse('*;=0.5') == ('*', '*', {})
- assert parse('*;q=foobar') == ('*', '*', {'q': 'foobar'})
- assert parse('image/gif; level=2; q=2') == (
- 'image', 'gif', {'level': '2', 'q': '2'})
- assert parse('application/xml;q=') == ('application', 'xml', {})
- assert parse('application/xml ;q=') == ('application', 'xml', {})
- assert parse(' *; q =;') == ('*', '*', {})
- assert parse(' *; q=.2') == ('*', '*', {'q': '.2'})
-
-def test_parse_media_range():
- parse = parse_media_range
- assert parse('application/*;q=0.5') == ('application', '*', {'q': '0.5'})
- assert parse('text/plain') == ('text', 'plain', {'q': '1'})
- assert parse('*') == ('*', '*', {'q': '1'})
- assert parse(';q=0.5') == ('*', '*', {'q': '0.5'})
- assert parse('*;q=0.5') == ('*', '*', {'q': '0.5'})
- assert parse('*;q=1') == ('*', '*', {'q': '1'})
- assert parse('*;q=') == ('*', '*', {'q': '1'})
- assert parse('*;q=-1') == ('*', '*', {'q': '1'})
- assert parse('*;q=foobar') == ('*', '*', {'q': '1'})
- assert parse('*;q=0.0001') == ('*', '*', {'q': '0.0001'})
- assert parse('*;q=1000.0') == ('*', '*', {'q': '1'})
- assert parse('*;q=0') == ('*', '*', {'q': '0'})
- assert parse('*;q=0.0000') == ('*', '*', {'q': '0.0000'})
- assert parse('*;q=1.0001') == ('*', '*', {'q': '1'})
- assert parse('*;q=2') == ('*', '*', {'q': '1'})
- assert parse('*;q=1e3') == ('*', '*', {'q': '1'})
- assert parse('image/gif; level=2') == (
- 'image', 'gif', {'level': '2', 'q': '1'})
- assert parse('image/gif; level=2; q=0.5') == (
- 'image', 'gif', {'level': '2', 'q': '0.5'})
- assert parse('image/gif; level=2; q=2') == (
- 'image', 'gif', {'level': '2', 'q': '1'})
- assert parse('application/xml') == ('application', 'xml', {'q': '1'})
- assert parse('application/xml;q=1') == ('application', 'xml', {'q': '1'})
- assert parse('application/xml;q=') == ('application', 'xml', {'q': '1'})
- assert parse('application/xml ;q=') == ('application', 'xml', {'q': '1'})
- assert parse('application/xml ; q=1;b=other') == (
- 'application', 'xml', {'q': '1', 'b': 'other'})
- assert parse('application/xml ; q=2;b=other') == (
- 'application', 'xml', {'q': '1', 'b': 'other'})
- assert parse(' *; q =;') == ('*', '*', {'q': '1'})
- assert parse(' *; q=.2') == ('*', '*', {'q': '.2'})
-
-def test_fitness_and_quality_parsed():
- faq = fitness_and_quality_parsed
- assert faq('*/*;q=0.7', [
- ('foo', 'bar', {'q': '0.5'})]) == (0, 0.5)
- assert faq('foo/*;q=0.7', [
- ('foo', 'bar', {'q': '0.5'})]) == (100, 0.5)
- assert faq('*/bar;q=0.7', [
- ('foo', 'bar', {'q': '0.5'})]) == (10, 0.5)
- assert faq('foo/bar;q=0.7', [
- ('foo', 'bar', {'q': '0.5'})]) == (110, 0.5)
- assert faq('text/html;q=0.7', [
- ('foo', 'bar', {'q': '0.5'})]) == (-1, 0)
- assert faq('text/html;q=0.7', [
- ('text', 'bar', {'q': '0.5'})]) == (-1, 0)
- assert faq('text/html;q=0.7', [
- ('foo', 'html', {'q': '0.5'})]) == (-1, 0)
- assert faq('text/html;q=0.7', [
- ('text', '*', {'q': '0.5'})]) == (100, 0.5)
- assert faq('text/html;q=0.7', [
- ('*', 'html', {'q': '0.5'})]) == (10, 0.5)
- assert faq('text/html;q=0.7', [
- ('*', '*', {'q': '0'}), ('text', 'html', {'q': '0.5'})]) == (110, 0.5)
- assert faq('text/html;q=0.7', [
- ('*', '*', {'q': '0.5'}), ('audio', '*', {'q': '0'})]) == (0, 0.5)
- assert faq('audio/mp3;q=0.7', [
- ('*', '*', {'q': '0'}), ('audio', '*', {'q': '0.5'})]) == (100, 0.5)
- assert faq('*/mp3;q=0.7', [
- ('foo', 'mp3', {'q': '0.5'}), ('audio', '*', {'q': '0'})]) == (10, 0.5)
- assert faq('audio/mp3;q=0.7', [
- ('audio', 'ogg', {'q': '0'}), ('*', 'mp3', {'q': '0.5'})]) == (10, 0.5)
- assert faq('audio/mp3;q=0.7', [
- ('*', 'ogg', {'q': '0'}), ('*', 'mp3', {'q': '0.5'})]) == (10, 0.5)
- assert faq('text/html;q=0.7', [
- ('text', 'plain', {'q': '0'}),
- ('plain', 'html', {'q': '0'}),
- ('text', 'html', {'q': '0.5'}),
- ('html', 'text', {'q': '0'})]) == (110, 0.5)
- assert faq('text/html;q=0.7;level=2', [
- ('plain', 'html', {'q': '0', 'level': '2'}),
- ('text', '*', {'q': '0.5', 'level': '3'}),
- ('*', 'html', {'q': '0.5', 'level': '2'}),
- ('image', 'gif', {'q': '0.5', 'level': '2'})]) == (100, 0.5)
- assert faq('text/html;q=0.7;level=2', [
- ('text', 'plain', {'q': '0'}), ('text', 'html', {'q': '0'}),
- ('text', 'plain', {'q': '0', 'level': '2'}),
- ('text', 'html', {'q': '0.5', 'level': '2'}),
- ('*', '*', {'q': '0', 'level': '2'}),
- ('text', 'html', {'q': '0', 'level': '3'})]) == (111, 0.5)
- assert faq('text/html;q=0.7;level=2;opt=3', [
- ('text', 'html', {'q': '0'}),
- ('text', 'html', {'q': '0', 'level': '2'}),
- ('text', 'html', {'q': '0', 'opt': '3'}),
- ('*', '*', {'q': '0', 'level': '2', 'opt': '3'}),
- ('text', 'html', {'q': '0', 'level': '3', 'opt': '3'}),
- ('text', 'html', {'q': '0.5', 'level': '2', 'opt': '3'}),
- ('*', '*', {'q': '0', 'level': '3', 'opt': '3'})]) == (112, 0.5)
-
-def test_quality_parsed():
- qp = quality_parsed
- assert qp('image/gif;q=0.7', [('image', 'jpg', {'q': '0.5'})]) == 0
- assert qp('image/gif;q=0.7', [('image', '*', {'q': '0.5'})]) == 0.5
- assert qp('audio/mp3;q=0.7;quality=100', [
- ('*', '*', {'q': '0', 'quality': '100'}),
- ('audio', '*', {'q': '0', 'quality': '100'}),
- ('*', 'mp3', {'q': '0', 'quality': '100'}),
- ('audio', 'mp3', {'q': '0', 'quality': '50'}),
- ('audio', 'mp3', {'q': '0.5', 'quality': '100'}),
- ('audio', 'mp3', {'q': '0.5'})]) == 0.5
-
-def test_quality():
- assert quality('text/html',
- 'text/*;q=0.3, text/html;q=0.75, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.75
- assert quality('text/html;level=2',
- 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.4
- assert quality('text/plain',
- 'text/*;q=0.25, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.25
- assert quality('plain/text',
- 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.5
- assert quality('text/html;level=1',
- 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 1
- assert quality('image/jpeg',
- 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.5
- assert quality('text/html;level=2',
- 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,'
- ' text/html;level=2;q=0.375, */*;q=0.5') == 0.375
- assert quality('text/html;level=3',
- 'text/*;q=0.3, text/html;q=0.75, text/html;level=1,'
- ' text/html;level=2;q=0.4, */*;q=0.5') == 0.75
-
-def test_best_match():
- bm = best_match
- assert bm([], '*/*') == ''
- assert bm(['application/xbel+xml', 'text/xml'],
- 'text/*;q=0.5,*/*; q=0.1') == 'text/xml'
- assert bm(['application/xbel+xml', 'audio/mp3'],
- 'text/*;q=0.5,*/*; q=0.1') == 'application/xbel+xml'
- assert bm(['application/xbel+xml', 'audio/mp3'],
- 'text/*;q=0.5,*/mp3; q=0.1') == 'audio/mp3'
- assert bm(['application/xbel+xml', 'text/plain', 'text/html'],
- 'text/*;q=0.5,*/plain; q=0.1') == 'text/plain'
- assert bm(['application/xbel+xml', 'text/html', 'text/xhtml'],
- 'text/*;q=0.1,*/xhtml; q=0.5') == 'text/html'
- assert bm(['application/xbel+xml', 'text/html', 'text/xhtml'],
- '*/html;q=0.1,*/xhtml; q=0.5') == 'text/xhtml'
- assert bm(['application/xbel+xml', 'application/xml'],
- 'application/xbel+xml') == 'application/xbel+xml'
- assert bm(['application/xbel+xml', 'application/xml'],
- 'application/xbel+xml; q=1') == 'application/xbel+xml'
- assert bm(['application/xbel+xml', 'application/xml'],
- 'application/xml; q=1') == 'application/xml'
- assert bm(['application/xbel+xml', 'application/xml'],
- 'application/*; q=1') == 'application/xbel+xml'
- assert bm(['application/xbel+xml', 'application/xml'],
- '*/*, application/xml') == 'application/xml'
- assert bm(['application/xbel+xml', 'text/xml'],
- 'text/*;q=0.5,*/*; q=0.1') == 'text/xml'
- assert bm(['application/xbel+xml', 'text/xml'],
- 'text/html,application/atom+xml; q=0.9') == ''
- assert bm(['application/json', 'text/html'],
- 'application/json, text/javascript, */*') == 'application/json'
- assert bm(['application/json', 'text/html'],
- 'application/json, text/html;q=0.9') == 'application/json'
- assert bm(['image/*', 'application/xml'], 'image/png') == 'image/*'
- assert bm(['image/*', 'application/xml'], 'image/*') == 'image/*'
-
-def test_illformed_best_match():
- bm = best_match
- assert bm(['image/png', 'image/jpeg', 'image/gif', 'text/html'],
- 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'image/jpeg'
- assert bm(['image/png', 'image/jpg', 'image/tif', 'text/html'],
- 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'text/html'
- assert bm(['image/png', 'image/jpg', 'image/tif', 'audio/mp3'],
- 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'image/png'
-
-def test_sorted_match():
- dm = desired_matches
- assert dm(['text/html', 'application/xml'],
- 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,'
- 'text/plain;q=0.8,image/png') == ['text/html', 'application/xml']
- assert dm(['text/html', 'application/xml'],
- 'application/xml,application/json') == ['application/xml']
- assert dm(['text/xhtml', 'text/plain', 'application/xhtml'],
- 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,'
- 'text/plain;q=0.8,image/png') == ['text/plain']
+# (c) 2010 Ch. Zwerschke and contributors +# This module is part of the Python Paste Project and is released under +# the MIT License: http://www.opensource.org/licenses/mit-license.php + +from paste.util.mimeparse import * + +def test_parse_mime_type(): + parse = parse_mime_type + assert parse('*/*') == ('*', '*', {}) + assert parse('text/html') == ('text', 'html', {}) + assert parse('audio/*; q=0.2') == ('audio', '*', {'q': '0.2'}) + assert parse('text/x-dvi;level=1') == ('text', 'x-dvi', {'level': '1'}) + assert parse('image/gif; level=2; q=0.4') == ( + 'image', 'gif', {'level': '2', 'q': '0.4'}) + assert parse('application/xhtml;level=3;q=0.5') == ( + 'application', 'xhtml', {'level': '3', 'q': '0.5'}) + assert parse('application/xml') == ('application', 'xml', {}) + assert parse('application/xml;q=1') == ('application', 'xml', {'q': '1'}) + assert parse('application/xml ; q=1;b=other') == ( + 'application', 'xml', {'q': '1', 'b': 'other'}) + assert parse('application/xml ; q=2;b=other') == ( + 'application', 'xml', {'q': '2', 'b': 'other'}) + assert parse('application/xhtml;q=0.5') == ( + 'application', 'xhtml', {'q': '0.5'}) + assert parse('application/xhtml;q=0.5;ver=1.2') == ( + 'application', 'xhtml', {'q': '0.5', 'ver': '1.2'}) + +def test_parse_illformed_mime_type(): + parse = parse_mime_type + assert parse('*') == ('*', '*', {}) + assert parse('text') == ('text', '*', {}) + assert parse('text/') == ('text', '*', {}) + assert parse('/plain') == ('*', 'plain', {}) + assert parse('/') == ('*', '*', {}) + assert parse('text/plain;') == ('text', 'plain', {}) + assert parse(';q=0.5') == ('*', '*', {'q': '0.5'}) + assert parse('*; q=.2') == ('*', '*', {'q': '.2'}) + assert parse('image; q=.7; level=3') == ( + 'image', '*', {'q': '.7', 'level': '3'}) + assert parse('*;q=1') == ('*', '*', {'q': '1'}) + assert parse('*;q=') == ('*', '*', {}) + assert parse('*;=0.5') == ('*', '*', {}) + assert parse('*;q=foobar') == ('*', '*', {'q': 'foobar'}) + assert parse('image/gif; level=2; q=2') == ( + 'image', 'gif', {'level': '2', 'q': '2'}) + assert parse('application/xml;q=') == ('application', 'xml', {}) + assert parse('application/xml ;q=') == ('application', 'xml', {}) + assert parse(' *; q =;') == ('*', '*', {}) + assert parse(' *; q=.2') == ('*', '*', {'q': '.2'}) + +def test_parse_media_range(): + parse = parse_media_range + assert parse('application/*;q=0.5') == ('application', '*', {'q': '0.5'}) + assert parse('text/plain') == ('text', 'plain', {'q': '1'}) + assert parse('*') == ('*', '*', {'q': '1'}) + assert parse(';q=0.5') == ('*', '*', {'q': '0.5'}) + assert parse('*;q=0.5') == ('*', '*', {'q': '0.5'}) + assert parse('*;q=1') == ('*', '*', {'q': '1'}) + assert parse('*;q=') == ('*', '*', {'q': '1'}) + assert parse('*;q=-1') == ('*', '*', {'q': '1'}) + assert parse('*;q=foobar') == ('*', '*', {'q': '1'}) + assert parse('*;q=0.0001') == ('*', '*', {'q': '0.0001'}) + assert parse('*;q=1000.0') == ('*', '*', {'q': '1'}) + assert parse('*;q=0') == ('*', '*', {'q': '0'}) + assert parse('*;q=0.0000') == ('*', '*', {'q': '0.0000'}) + assert parse('*;q=1.0001') == ('*', '*', {'q': '1'}) + assert parse('*;q=2') == ('*', '*', {'q': '1'}) + assert parse('*;q=1e3') == ('*', '*', {'q': '1'}) + assert parse('image/gif; level=2') == ( + 'image', 'gif', {'level': '2', 'q': '1'}) + assert parse('image/gif; level=2; q=0.5') == ( + 'image', 'gif', {'level': '2', 'q': '0.5'}) + assert parse('image/gif; level=2; q=2') == ( + 'image', 'gif', {'level': '2', 'q': '1'}) + assert parse('application/xml') == ('application', 'xml', {'q': '1'}) + assert parse('application/xml;q=1') == ('application', 'xml', {'q': '1'}) + assert parse('application/xml;q=') == ('application', 'xml', {'q': '1'}) + assert parse('application/xml ;q=') == ('application', 'xml', {'q': '1'}) + assert parse('application/xml ; q=1;b=other') == ( + 'application', 'xml', {'q': '1', 'b': 'other'}) + assert parse('application/xml ; q=2;b=other') == ( + 'application', 'xml', {'q': '1', 'b': 'other'}) + assert parse(' *; q =;') == ('*', '*', {'q': '1'}) + assert parse(' *; q=.2') == ('*', '*', {'q': '.2'}) + +def test_fitness_and_quality_parsed(): + faq = fitness_and_quality_parsed + assert faq('*/*;q=0.7', [ + ('foo', 'bar', {'q': '0.5'})]) == (0, 0.5) + assert faq('foo/*;q=0.7', [ + ('foo', 'bar', {'q': '0.5'})]) == (100, 0.5) + assert faq('*/bar;q=0.7', [ + ('foo', 'bar', {'q': '0.5'})]) == (10, 0.5) + assert faq('foo/bar;q=0.7', [ + ('foo', 'bar', {'q': '0.5'})]) == (110, 0.5) + assert faq('text/html;q=0.7', [ + ('foo', 'bar', {'q': '0.5'})]) == (-1, 0) + assert faq('text/html;q=0.7', [ + ('text', 'bar', {'q': '0.5'})]) == (-1, 0) + assert faq('text/html;q=0.7', [ + ('foo', 'html', {'q': '0.5'})]) == (-1, 0) + assert faq('text/html;q=0.7', [ + ('text', '*', {'q': '0.5'})]) == (100, 0.5) + assert faq('text/html;q=0.7', [ + ('*', 'html', {'q': '0.5'})]) == (10, 0.5) + assert faq('text/html;q=0.7', [ + ('*', '*', {'q': '0'}), ('text', 'html', {'q': '0.5'})]) == (110, 0.5) + assert faq('text/html;q=0.7', [ + ('*', '*', {'q': '0.5'}), ('audio', '*', {'q': '0'})]) == (0, 0.5) + assert faq('audio/mp3;q=0.7', [ + ('*', '*', {'q': '0'}), ('audio', '*', {'q': '0.5'})]) == (100, 0.5) + assert faq('*/mp3;q=0.7', [ + ('foo', 'mp3', {'q': '0.5'}), ('audio', '*', {'q': '0'})]) == (10, 0.5) + assert faq('audio/mp3;q=0.7', [ + ('audio', 'ogg', {'q': '0'}), ('*', 'mp3', {'q': '0.5'})]) == (10, 0.5) + assert faq('audio/mp3;q=0.7', [ + ('*', 'ogg', {'q': '0'}), ('*', 'mp3', {'q': '0.5'})]) == (10, 0.5) + assert faq('text/html;q=0.7', [ + ('text', 'plain', {'q': '0'}), + ('plain', 'html', {'q': '0'}), + ('text', 'html', {'q': '0.5'}), + ('html', 'text', {'q': '0'})]) == (110, 0.5) + assert faq('text/html;q=0.7;level=2', [ + ('plain', 'html', {'q': '0', 'level': '2'}), + ('text', '*', {'q': '0.5', 'level': '3'}), + ('*', 'html', {'q': '0.5', 'level': '2'}), + ('image', 'gif', {'q': '0.5', 'level': '2'})]) == (100, 0.5) + assert faq('text/html;q=0.7;level=2', [ + ('text', 'plain', {'q': '0'}), ('text', 'html', {'q': '0'}), + ('text', 'plain', {'q': '0', 'level': '2'}), + ('text', 'html', {'q': '0.5', 'level': '2'}), + ('*', '*', {'q': '0', 'level': '2'}), + ('text', 'html', {'q': '0', 'level': '3'})]) == (111, 0.5) + assert faq('text/html;q=0.7;level=2;opt=3', [ + ('text', 'html', {'q': '0'}), + ('text', 'html', {'q': '0', 'level': '2'}), + ('text', 'html', {'q': '0', 'opt': '3'}), + ('*', '*', {'q': '0', 'level': '2', 'opt': '3'}), + ('text', 'html', {'q': '0', 'level': '3', 'opt': '3'}), + ('text', 'html', {'q': '0.5', 'level': '2', 'opt': '3'}), + ('*', '*', {'q': '0', 'level': '3', 'opt': '3'})]) == (112, 0.5) + +def test_quality_parsed(): + qp = quality_parsed + assert qp('image/gif;q=0.7', [('image', 'jpg', {'q': '0.5'})]) == 0 + assert qp('image/gif;q=0.7', [('image', '*', {'q': '0.5'})]) == 0.5 + assert qp('audio/mp3;q=0.7;quality=100', [ + ('*', '*', {'q': '0', 'quality': '100'}), + ('audio', '*', {'q': '0', 'quality': '100'}), + ('*', 'mp3', {'q': '0', 'quality': '100'}), + ('audio', 'mp3', {'q': '0', 'quality': '50'}), + ('audio', 'mp3', {'q': '0.5', 'quality': '100'}), + ('audio', 'mp3', {'q': '0.5'})]) == 0.5 + +def test_quality(): + assert quality('text/html', + 'text/*;q=0.3, text/html;q=0.75, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.75 + assert quality('text/html;level=2', + 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.4 + assert quality('text/plain', + 'text/*;q=0.25, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.25 + assert quality('plain/text', + 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.5 + assert quality('text/html;level=1', + 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 1 + assert quality('image/jpeg', + 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.5 + assert quality('text/html;level=2', + 'text/*;q=0.3, text/html;q=0.7, text/html;level=1,' + ' text/html;level=2;q=0.375, */*;q=0.5') == 0.375 + assert quality('text/html;level=3', + 'text/*;q=0.3, text/html;q=0.75, text/html;level=1,' + ' text/html;level=2;q=0.4, */*;q=0.5') == 0.75 + +def test_best_match(): + bm = best_match + assert bm([], '*/*') == '' + assert bm(['application/xbel+xml', 'text/xml'], + 'text/*;q=0.5,*/*; q=0.1') == 'text/xml' + assert bm(['application/xbel+xml', 'audio/mp3'], + 'text/*;q=0.5,*/*; q=0.1') == 'application/xbel+xml' + assert bm(['application/xbel+xml', 'audio/mp3'], + 'text/*;q=0.5,*/mp3; q=0.1') == 'audio/mp3' + assert bm(['application/xbel+xml', 'text/plain', 'text/html'], + 'text/*;q=0.5,*/plain; q=0.1') == 'text/plain' + assert bm(['application/xbel+xml', 'text/html', 'text/xhtml'], + 'text/*;q=0.1,*/xhtml; q=0.5') == 'text/html' + assert bm(['application/xbel+xml', 'text/html', 'text/xhtml'], + '*/html;q=0.1,*/xhtml; q=0.5') == 'text/xhtml' + assert bm(['application/xbel+xml', 'application/xml'], + 'application/xbel+xml') == 'application/xbel+xml' + assert bm(['application/xbel+xml', 'application/xml'], + 'application/xbel+xml; q=1') == 'application/xbel+xml' + assert bm(['application/xbel+xml', 'application/xml'], + 'application/xml; q=1') == 'application/xml' + assert bm(['application/xbel+xml', 'application/xml'], + 'application/*; q=1') == 'application/xbel+xml' + assert bm(['application/xbel+xml', 'application/xml'], + '*/*, application/xml') == 'application/xml' + assert bm(['application/xbel+xml', 'text/xml'], + 'text/*;q=0.5,*/*; q=0.1') == 'text/xml' + assert bm(['application/xbel+xml', 'text/xml'], + 'text/html,application/atom+xml; q=0.9') == '' + assert bm(['application/json', 'text/html'], + 'application/json, text/javascript, */*') == 'application/json' + assert bm(['application/json', 'text/html'], + 'application/json, text/html;q=0.9') == 'application/json' + assert bm(['image/*', 'application/xml'], 'image/png') == 'image/*' + assert bm(['image/*', 'application/xml'], 'image/*') == 'image/*' + +def test_illformed_best_match(): + bm = best_match + assert bm(['image/png', 'image/jpeg', 'image/gif', 'text/html'], + 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'image/jpeg' + assert bm(['image/png', 'image/jpg', 'image/tif', 'text/html'], + 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'text/html' + assert bm(['image/png', 'image/jpg', 'image/tif', 'audio/mp3'], + 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2') == 'image/png' + +def test_sorted_match(): + dm = desired_matches + assert dm(['text/html', 'application/xml'], + 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,' + 'text/plain;q=0.8,image/png') == ['text/html', 'application/xml'] + assert dm(['text/html', 'application/xml'], + 'application/xml,application/json') == ['application/xml'] + assert dm(['text/xhtml', 'text/plain', 'application/xhtml'], + 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,' + 'text/plain;q=0.8,image/png') == ['text/plain'] diff --git a/tests/test_wsgiwrappers.py b/tests/test_wsgiwrappers.py index b552f86..833b4f2 100644 --- a/tests/test_wsgiwrappers.py +++ b/tests/test_wsgiwrappers.py @@ -4,6 +4,7 @@ import cgi from paste.fixture import TestApp from paste.wsgiwrappers import WSGIRequest, WSGIResponse +import six class AssertApp(object): def __init__(self, assertfunc): @@ -42,7 +43,7 @@ def test_wsgirequest_charset(): # Tanaka, '田中' app = TestApp(AssertApp(assertfunc=valid_name(u'田中', encoding='UTF-8'))) res = app.get('/?name=%E7%94%B0%E4%B8%AD') - + # Nippon (Japan), '日本' app = TestApp(AssertApp(assertfunc=valid_name(u'日本', encoding='UTF-8', post=True))) @@ -79,23 +80,23 @@ def test_wsgirequest_charset_fileupload(): assert isinstance(fs, cgi.FieldStorage) assert isinstance(fs.filename, str) assert fs.filename == '寿司.txt' - assert fs.value == 'Sushi' + assert fs.value == b'Sushi' request.charset = 'UTF-8' assert len(request.POST) == 1 assert isinstance(request.POST.keys()[0], str) fs = request.POST['thefile'] assert isinstance(fs, cgi.FieldStorage) - assert isinstance(fs.filename, unicode) + assert isinstance(fs.filename, six.text_type) assert fs.filename == u'寿司.txt' - assert fs.value == 'Sushi' + assert fs.value == b'Sushi' request.charset = None - assert fs.value == 'Sushi' + assert fs.value == b'Sushi' return [] app = TestApp(handle_fileupload) - res = app.post('/', upload_files=[('thefile', '寿司.txt', 'Sushi')]) + res = app.post('/', upload_files=[('thefile', '寿司.txt', b'Sushi')]) def test_wsgiresponse_charset(): response = WSGIResponse(mimetype='text/html; charset=UTF-8') @@ -106,7 +107,7 @@ def test_wsgiresponse_charset(): response.write('test3') status, headers, content = response.wsgi_response() for data in content: - assert isinstance(data, str) + assert isinstance(data, six.binary_type) WSGIResponse.defaults._push_object(dict(content_type='text/html', charset='iso-8859-1')) @@ -117,7 +118,7 @@ def test_wsgiresponse_charset(): response.write('test3') status, headers, content = response.wsgi_response() for data in content: - assert isinstance(data, str) + assert isinstance(data, six.binary_type) finally: WSGIResponse.defaults._pop_object() @@ -130,7 +131,7 @@ def test_wsgiresponse_charset(): response.write(u'test1') status, headers, content = response.wsgi_response() for data in content: - assert isinstance(data, unicode) + assert isinstance(data, six.text_type) finally: WSGIResponse.defaults._pop_object() @@ -141,6 +142,6 @@ def test_wsgiresponse_charset(): response.write(u'test1') status, headers, content = response.wsgi_response() for data in content: - assert isinstance(data, unicode) + assert isinstance(data, six.text_type) finally: WSGIResponse.defaults._pop_object() diff --git a/tests/urlparser_data/hook/app.py b/tests/urlparser_data/hook/app.py index d2714e5..1a98013 100644 --- a/tests/urlparser_data/hook/app.py +++ b/tests/urlparser_data/hook/app.py @@ -1,5 +1,9 @@ +import six + def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) - return ['user: %s' % environ['app.user']] + body = 'user: %s' % environ['app.user'] + if six.PY3: + body = body.encode('ascii') + return [body] - diff --git a/tests/urlparser_data/hook/index.py b/tests/urlparser_data/hook/index.py index 49e89f0..92f3d66 100644 --- a/tests/urlparser_data/hook/index.py +++ b/tests/urlparser_data/hook/index.py @@ -1,4 +1,9 @@ +import six + def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html')]) - return ['index: %s' % environ['app.user']] + body = 'index: %s' % environ['app.user'] + if six.PY3: + body = body.encode('ascii') + return [body] diff --git a/tests/urlparser_data/not_found/simple/__init__.py b/tests/urlparser_data/not_found/simple/__init__.py index f1e7faa..7186daa 100644 --- a/tests/urlparser_data/not_found/simple/__init__.py +++ b/tests/urlparser_data/not_found/simple/__init__.py @@ -1,3 +1,3 @@ def not_found_hook(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) - return ['not found'] + return [b'not found'] diff --git a/tests/urlparser_data/not_found/user/list.py b/tests/urlparser_data/not_found/user/list.py index f6228f0..fd7482f 100644 --- a/tests/urlparser_data/not_found/user/list.py +++ b/tests/urlparser_data/not_found/user/list.py @@ -1,3 +1,8 @@ +import six + def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) - return ['user: %s' % environ.get('app.user')] + body = 'user: %s' % environ.get('app.user') + if six.PY3: + body = body.encode('ascii') + return [body] diff --git a/tests/urlparser_data/python/simpleapp.py b/tests/urlparser_data/python/simpleapp.py index cbef9f1..7a36ce9 100644 --- a/tests/urlparser_data/python/simpleapp.py +++ b/tests/urlparser_data/python/simpleapp.py @@ -1,6 +1,5 @@ def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html'), ('test-header', 'TEST!')]) - return ['test1'] + return [b'test1'] - diff --git a/tests/urlparser_data/python/stream.py b/tests/urlparser_data/python/stream.py index 121b4d1..e81fd1c 100644 --- a/tests/urlparser_data/python/stream.py +++ b/tests/urlparser_data/python/stream.py @@ -1,7 +1,7 @@ def stream(): def app(environ, start_response): writer = start_response('200 OK', [('Content-type', 'text/html')]) - writer('te') - writer('st') - return ['2'] + writer(b'te') + writer(b'st') + return [b'2'] return app diff --git a/tests/urlparser_data/python/sub/simpleapp.py b/tests/urlparser_data/python/sub/simpleapp.py index fd90966..88bd975 100644 --- a/tests/urlparser_data/python/sub/simpleapp.py +++ b/tests/urlparser_data/python/sub/simpleapp.py @@ -1,6 +1,4 @@ def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/html'), ('test-header', 'TEST!')]) - return ['subsimple'] - - + return [b'subsimple'] |