summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Smith <smithdc@gmail.com>2020-11-07 20:57:17 +0000
committerDavid Smith <smithdc@gmail.com>2020-11-07 20:57:17 +0000
commitd5df159bd27b41c77042e8814ab4f37ebdcea18a (patch)
treeebdbc51934f9546d43e3f172e376e43489f0c72c
parent3d09494d80713a32d9bc52e457bff16fb6ba285c (diff)
downloadwebtest-d5df159bd27b41c77042e8814ab4f37ebdcea18a.tar.gz
Dropped support for Python 2.7 and 3.5
-rw-r--r--tests/compat.py2
-rw-r--r--tests/test_app.py44
-rw-r--r--tests/test_authorisation.py2
-rw-r--r--tests/test_debugapp.py12
-rw-r--r--tests/test_ext.py2
-rw-r--r--tests/test_forms.py61
-rw-r--r--tests/test_http.py1
-rw-r--r--tests/test_lint.py63
-rw-r--r--tests/test_response.py22
-rw-r--r--tests/test_sel.py1
-rw-r--r--tests/test_utils.py5
-rw-r--r--tox.ini2
-rw-r--r--webtest/app.py64
-rw-r--r--webtest/compat.py31
-rw-r--r--webtest/debugapp.py21
-rw-r--r--webtest/ext.py1
-rw-r--r--webtest/forms.py21
-rw-r--r--webtest/http.py17
-rw-r--r--webtest/lint.py37
-rw-r--r--webtest/response.py59
-rw-r--r--webtest/sel.py3
-rw-r--r--webtest/utils.py25
22 files changed, 177 insertions, 319 deletions
diff --git a/tests/compat.py b/tests/compat.py
index bfde62b..8264626 100644
--- a/tests/compat.py
+++ b/tests/compat.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import unittest # noqa
try:
diff --git a/tests/test_app.py b/tests/test_app.py
index c823baa..4bc8298 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -1,16 +1,13 @@
-# -*- coding: utf-8 -*-
-from six import binary_type
+from http import cookiejar as http_cookiejar
from webob import Request
from webob import Response
from webtest.compat import to_bytes
-from webtest.compat import PY3
from collections import OrderedDict
from webtest.debugapp import debug_app
from webtest import http
from tests.compat import unittest
import os
-import six
-import mock
+from unittest import mock
import webtest
@@ -31,11 +28,11 @@ class TestApp(unittest.TestCase):
def test_encode_multipart(self):
data = self.app.encode_multipart(
- [], [('file', 'data.txt', six.b('data'))])
+ [], [('file', 'data.txt', b'data')])
self.assertIn(to_bytes('data.txt'), data[-1])
data = self.app.encode_multipart(
- [], [(six.b('file'), six.b('data.txt'), six.b('data'))])
+ [], [(b'file', b'data.txt', b'data')])
self.assertIn(to_bytes('data.txt'), data[-1])
data = self.app.encode_multipart(
@@ -43,18 +40,18 @@ class TestApp(unittest.TestCase):
self.assertIn(to_bytes('name="key"'), data[-1])
data = self.app.encode_multipart(
- [(six.b('key'), six.b('value'))], [])
+ [(b'key', b'value')], [])
self.assertIn(to_bytes('name="key"'), data[-1])
def test_encode_multipart_content_type(self):
data = self.app.encode_multipart(
- [], [('file', 'data.txt', six.b('data'),
+ [], [('file', 'data.txt', b'data',
'text/x-custom-mime-type')])
self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'),
data[-1])
data = self.app.encode_multipart(
- [('file', webtest.Upload('data.txt', six.b('data'),
+ [('file', webtest.Upload('data.txt', b'data',
'text/x-custom-mime-type'))], [])
self.assertIn(to_bytes('Content-Type: text/x-custom-mime-type'),
data[-1])
@@ -136,21 +133,21 @@ class TestAppError(unittest.TestCase):
self.assertEqual(err.args, ('message blah',))
def test_app_error_with_bytes_message(self):
- resp = Response(six.u('\xe9').encode('utf8'))
+ resp = Response('\xe9'.encode('utf8'))
resp.charset = 'utf8'
err = webtest.AppError(to_bytes('message %s'), resp)
- self.assertEqual(err.args, (six.u('message \xe9'),))
+ self.assertEqual(err.args, ('message \xe9',))
def test_app_error_with_unicode(self):
- err = webtest.AppError(six.u('messag\xe9 %s'), six.u('\xe9'))
- self.assertEqual(err.args, (six.u('messag\xe9 \xe9'),))
+ err = webtest.AppError('messag\xe9 %s', '\xe9')
+ self.assertEqual(err.args, ('messag\xe9 \xe9',))
def test_app_error_misc(self):
- resp = Response(six.u('\xe9').encode('utf8'))
+ resp = Response('\xe9'.encode('utf8'))
resp.charset = ''
# dont check the output. just make sure it doesn't fail
webtest.AppError(to_bytes('message %s'), resp)
- webtest.AppError(six.u('messag\xe9 %s'), six.b('\xe9'))
+ webtest.AppError('messag\xe9 %s', b'\xe9')
class TestPasteVariables(unittest.TestCase):
@@ -177,7 +174,7 @@ class TestPasteVariables(unittest.TestCase):
class TestCookies(unittest.TestCase):
def test_supports_providing_cookiejar(self):
- cookiejar = six.moves.http_cookiejar.CookieJar()
+ cookiejar = http_cookiejar.CookieJar()
app = webtest.TestApp(debug_app, cookiejar=cookiejar)
self.assertIs(cookiejar, app.cookiejar)
@@ -287,7 +284,7 @@ class TestCookies(unittest.TestCase):
else:
self.fail('testapp.cookies should be read-only')
- @mock.patch('six.moves.http_cookiejar.time.time')
+ @mock.patch('http.cookiejar.time.time')
def test_expires_cookies(self, mock_time):
def cookie_app(environ, start_response):
status = to_bytes("200 OK")
@@ -361,7 +358,6 @@ class TestCookies(unittest.TestCase):
self.assertEqual(dict(res.request.cookies), {'spam': 'eggs'})
def test_cookie_policy(self):
- from six.moves import http_cookiejar
def cookie_app(environ, start_response):
status = to_bytes("200 OK")
@@ -496,7 +492,7 @@ def get_submit_app(form_id, form_fields_text):
</html>
"""
body = body_head + "".join(body_parts) + body_foot
- if not isinstance(body, binary_type):
+ if not isinstance(body, bytes):
body = body.encode('utf8')
headers = [
('Content-Type', 'text/html; charset=utf-8'),
@@ -510,9 +506,7 @@ class TestFieldOrder(unittest.TestCase):
def test_submit_with_file_upload(self):
uploaded_file_name = 'test.txt'
- uploaded_file_contents = 'test content file upload'
- if PY3:
- uploaded_file_contents = to_bytes(uploaded_file_contents)
+ uploaded_file_contents = to_bytes('test content file upload')
deform_upload_file_app = get_submit_app('deform',
deform_upload_fields_text)
@@ -543,9 +537,7 @@ Submit:Submit
def test_post_with_file_upload(self):
uploaded_file_name = 'test.txt'
- uploaded_file_contents = 'test content file upload'
- if PY3:
- uploaded_file_contents = to_bytes(uploaded_file_contents)
+ uploaded_file_contents = to_bytes('test content file upload')
deform_upload_file_app = get_submit_app('deform',
deform_upload_fields_text)
diff --git a/tests/test_authorisation.py b/tests/test_authorisation.py
index 5cdc1e7..861b6e6 100644
--- a/tests/test_authorisation.py
+++ b/tests/test_authorisation.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
from webtest.debugapp import DebugApp
from tests.compat import unittest
from base64 import b64decode
diff --git a/tests/test_debugapp.py b/tests/test_debugapp.py
index 87c61a0..35fe381 100644
--- a/tests/test_debugapp.py
+++ b/tests/test_debugapp.py
@@ -1,11 +1,7 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
import os
import sys
-import six
import webtest
from webtest.debugapp import debug_app
-from webtest.compat import PY3
from webtest.compat import to_bytes
from webtest.compat import print_stderr
from webtest.app import AppError
@@ -112,7 +108,7 @@ class TestTesting(unittest.TestCase):
assert(False, "An AppError should be raised")
except AppError:
e = sys.exc_info()[1]
- assert six.text_type(e) \
+ assert str(e) \
== "Application had errors logged:\nsomelogs"
def test_request_obj(self):
@@ -171,16 +167,12 @@ class TestTesting(unittest.TestCase):
res = self.app.get('/')
res.charset = 'utf-8'
res.text = '°C'
- if not PY3:
- unicode(AssertionError(res))
str(AssertionError(res))
res.charset = None
- if not PY3:
- unicode(AssertionError(res))
str(AssertionError(res))
def test_fake_dict(self):
- class FakeDict(object):
+ class FakeDict:
def items(self):
return [('a', '10'), ('a', '20')]
self.app.post('/params', params=FakeDict())
diff --git a/tests/test_ext.py b/tests/test_ext.py
index f3b5cd9..2429387 100644
--- a/tests/test_ext.py
+++ b/tests/test_ext.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-# -*- coding: utf-8 -*-
from .compat import unittest
from webtest import ext
diff --git a/tests/test_forms.py b/tests/test_forms.py
index 47b1b66..d50c034 100644
--- a/tests/test_forms.py
+++ b/tests/test_forms.py
@@ -1,15 +1,9 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
import cgi
import os.path
import struct
import sys
import webtest
-import six
-from six import binary_type
-from six import PY3
from webob import Request
from webtest.debugapp import DebugApp
from webtest.compat import to_bytes
@@ -210,22 +204,22 @@ class TestInput(unittest.TestCase):
self.assertEqual(form['foo'].value, 'true')
self.assertEqual(form['foo'].selectedIndex, 0)
self.assertEqual(form.submit_fields(), [
- (u'__start__', u'item:mapping'),
+ ('__start__', 'item:mapping'),
('foo', 'true'),
- (u'__end__', u'item:mapping'),
- (u'__start__', u'item:mapping'),
- (u'__end__', u'item:mapping')])
+ ('__end__', 'item:mapping'),
+ ('__start__', 'item:mapping'),
+ ('__end__', 'item:mapping')])
res = app.get('/form.html')
form = res.forms['complex_radio_input_form']
self.assertEqual(form['foo'].value, 'true')
self.assertEqual(form['foo'].selectedIndex, 1)
self.assertEqual(form.submit_fields(), [
- (u'__start__', u'item:mapping'),
- (u'__end__', u'item:mapping'),
- (u'__start__', u'item:mapping'),
+ ('__start__', 'item:mapping'),
+ ('__end__', 'item:mapping'),
+ ('__start__', 'item:mapping'),
('foo', 'true'),
- (u'__end__', u'item:mapping')])
+ ('__end__', 'item:mapping')])
def test_input_unicode(self):
app = self.callFUT('form_unicode_inputs.html')
@@ -526,8 +520,8 @@ def select_app_unicode(environ, start_response):
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(status, headers)
- if not isinstance(body, binary_type):
- raise AssertionError('Body is not %s' % binary_type)
+ if not isinstance(body, bytes):
+ raise AssertionError('Body is not %s' % bytes)
return [body]
@@ -793,7 +787,7 @@ class TestSelect(unittest.TestCase):
self.assertIn("<p>You selected </p>", display, display)
-class SingleUploadFileApp(object):
+class SingleUploadFileApp:
body = b"""
<html>
@@ -829,7 +823,7 @@ class SingleUploadFileApp(object):
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(status, headers)
- assert(isinstance(body, binary_type))
+ assert(isinstance(body, bytes))
return [body]
def get_files_page(self, req):
@@ -856,10 +850,7 @@ class UploadBinaryApp(SingleUploadFileApp):
def get_files_page(self, req):
uploaded_files = [(k, v) for k, v in req.POST.items() if 'file' in k]
data = uploaded_files[0][1].value
- if PY3:
- data = struct.unpack(b'255h', data[:510])
- else:
- data = struct.unpack(str('255h'), data)
+ data = struct.unpack(b'255h', data[:510])
return b','.join([to_bytes(str(i)) for i in data])
@@ -882,13 +873,13 @@ class MultipleUploadFileApp(SingleUploadFileApp):
class TestFileUpload(unittest.TestCase):
def assertFile(self, name, contents, display, content_type=None):
- if isinstance(name, six.binary_type):
+ if isinstance(name, bytes):
text_name = name.decode('ascii')
else:
text_name = name
self.assertIn("<p>You selected '" + text_name + "'</p>",
display, display)
- if isinstance(contents, six.binary_type):
+ if isinstance(contents, bytes):
text_contents = contents.decode('ascii')
else:
text_contents = contents
@@ -911,8 +902,7 @@ class TestFileUpload(unittest.TestCase):
uploaded_file_name = os.path.join(os.path.dirname(__file__),
"__init__.py")
uploaded_file_contents = open(uploaded_file_name).read()
- if PY3:
- uploaded_file_contents = to_bytes(uploaded_file_contents)
+ uploaded_file_contents = to_bytes(uploaded_file_contents)
app = webtest.TestApp(SingleUploadFileApp())
res = app.get('/')
@@ -931,8 +921,7 @@ class TestFileUpload(unittest.TestCase):
uploaded_file_name = os.path.join(os.path.dirname(__file__),
"__init__.py")
uploaded_file_contents = open(uploaded_file_name).read()
- if PY3:
- uploaded_file_contents = to_bytes(uploaded_file_contents)
+ uploaded_file_contents = to_bytes(uploaded_file_contents)
app = webtest.TestApp(SingleUploadFileApp())
res = app.get('/')
@@ -963,7 +952,7 @@ class TestFileUpload(unittest.TestCase):
content_type='text/x-custom-type')
def test_file_upload_binary(self):
- binary_data = struct.pack(str('255h'), *range(0, 255))
+ binary_data = struct.pack('255h', *range(0, 255))
app = webtest.TestApp(UploadBinaryApp())
res = app.get('/')
single_form = res.forms["file_upload_form"]
@@ -975,14 +964,12 @@ class TestFileUpload(unittest.TestCase):
uploaded_file1_name = os.path.join(os.path.dirname(__file__),
"__init__.py")
uploaded_file1_contents = open(uploaded_file1_name).read()
- if PY3:
- uploaded_file1_contents = to_bytes(uploaded_file1_contents)
+ uploaded_file1_contents = to_bytes(uploaded_file1_contents)
uploaded_file2_name = __file__
uploaded_file2_name = os.path.join(os.path.dirname(__file__), 'html',
"404.html")
uploaded_file2_contents = open(uploaded_file2_name).read()
- if PY3:
- uploaded_file2_contents = to_bytes(uploaded_file2_contents)
+ uploaded_file2_contents = to_bytes(uploaded_file2_contents)
app = webtest.TestApp(MultipleUploadFileApp())
res = app.get('/')
@@ -1001,7 +988,7 @@ class TestFileUpload(unittest.TestCase):
self.assertFile(uploaded_file1_name, uploaded_file1_contents, display)
def test_post_int(self):
- binary_data = struct.pack(str('255h'), *range(0, 255))
+ binary_data = struct.pack('255h', *range(0, 255))
app = webtest.TestApp(SingleUploadFileApp())
res = app.get('/')
single_form = res.forms["file_upload_form"]
@@ -1011,7 +998,7 @@ class TestFileUpload(unittest.TestCase):
single_form.submit("button")
def test_invalid_types(self):
- binary_data = struct.pack(str('255h'), *range(0, 255))
+ binary_data = struct.pack('255h', *range(0, 255))
app = webtest.TestApp(SingleUploadFileApp())
res = app.get('/')
single_form = res.forms["file_upload_form"]
@@ -1029,8 +1016,8 @@ class TestFileUpload(unittest.TestCase):
except ValueError:
e = sys.exc_info()[1]
self.assertEquals(
- six.text_type(e),
- u('File content must be %s not %s' % (binary_type, int))
+ str(e),
+ u('File content must be %s not %s' % (bytes, int))
)
def test_invalid_uploadfiles(self):
diff --git a/tests/test_http.py b/tests/test_http.py
index f52a596..99a99ea 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
from tests.compat import unittest
from webob import Request
from webtest.debugapp import debug_app
diff --git a/tests/test_lint.py b/tests/test_lint.py
index 1a84a41..e263321 100644
--- a/tests/test_lint.py
+++ b/tests/test_lint.py
@@ -1,14 +1,10 @@
-# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
-
import sys
-from six import PY3
-from six import StringIO
from tests.compat import unittest
from webob import Request, Response
import warnings
-import mock
+from unittest import mock
+from io import StringIO
from webtest import TestApp
from webtest.compat import to_bytes
@@ -47,14 +43,10 @@ class TestLatin1Assertion(unittest.TestCase):
def test_valid_type(self):
value = "useful-inførmation-5"
- if not PY3:
- value = value.encode("latin1")
assert value == _assert_latin1_str(value, "fail")
def test_invalid_type(self):
value = b"useful-information-5"
- if not PY3:
- value = value.decode("utf8")
self.assertRaises(AssertionError, _assert_latin1_str, value, "fail")
@@ -162,41 +154,29 @@ class TestCheckContentType(unittest.TestCase):
class TestCheckHeaders(unittest.TestCase):
- @unittest.skipIf(PY3, 'unicode is str in Python3')
- def test_header_unicode_name(self):
- headers = [(u'X-Price', str('100'))]
- self.assertRaises(AssertionError, check_headers, headers)
-
- @unittest.skipIf(PY3, 'unicode is str in Python3')
- def test_header_unicode_value(self):
- headers = [(str('X-Price'), u'100')]
- self.assertRaises(AssertionError, check_headers, headers)
-
- @unittest.skipIf(not PY3, 'bytes is str in Python2')
def test_header_bytes_name(self):
headers = [(b'X-Price', '100')]
self.assertRaises(AssertionError, check_headers, headers)
- @unittest.skipIf(not PY3, 'bytes is str in Python2')
def test_header_bytes_value(self):
headers = [('X-Price', b'100')]
self.assertRaises(AssertionError, check_headers, headers)
def test_header_non_latin1_value(self):
- headers = [(str('X-Price'), '100€')]
+ headers = [('X-Price', '100€')]
self.assertRaises(AssertionError, check_headers, headers)
def test_header_non_latin1_name(self):
- headers = [('X-€', str('foo'))]
+ headers = [('X-€', 'foo')]
self.assertRaises(AssertionError, check_headers, headers)
class TestCheckEnviron(unittest.TestCase):
def test_no_query_string(self):
environ = {
- 'REQUEST_METHOD': str('GET'),
- 'SERVER_NAME': str('localhost'),
- 'SERVER_PORT': str('80'),
+ 'REQUEST_METHOD': 'GET',
+ 'SERVER_NAME': 'localhost',
+ 'SERVER_PORT': '80',
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
@@ -204,7 +184,7 @@ class TestCheckEnviron(unittest.TestCase):
'wsgi.multiprocess': None,
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
- 'PATH_INFO': str('/'),
+ 'PATH_INFO': '/',
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
@@ -216,9 +196,9 @@ class TestCheckEnviron(unittest.TestCase):
def test_no_valid_request(self):
environ = {
- 'REQUEST_METHOD': str('PROPFIND'),
- 'SERVER_NAME': str('localhost'),
- 'SERVER_PORT': str('80'),
+ 'REQUEST_METHOD': 'PROPFIND',
+ 'SERVER_NAME': 'localhost',
+ 'SERVER_PORT': '80',
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
@@ -226,8 +206,8 @@ class TestCheckEnviron(unittest.TestCase):
'wsgi.multiprocess': None,
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
- 'PATH_INFO': str('/'),
- 'QUERY_STRING': str(''),
+ 'PATH_INFO': '/',
+ 'QUERY_STRING': '',
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
@@ -239,14 +219,11 @@ class TestCheckEnviron(unittest.TestCase):
"about REQUEST_METHOD")
def test_handles_native_strings_in_variables(self):
- # "native string" means unicode in py3, but bytes in py2
path = '/umläut'
- if not PY3:
- path = path.encode('utf-8')
environ = {
- 'REQUEST_METHOD': str('GET'),
- 'SERVER_NAME': str('localhost'),
- 'SERVER_PORT': str('80'),
+ 'REQUEST_METHOD': 'GET',
+ 'SERVER_NAME': 'localhost',
+ 'SERVER_PORT': '80',
'wsgi.version': (1, 0, 1),
'wsgi.input': StringIO('test'),
'wsgi.errors': StringIO(),
@@ -255,7 +232,7 @@ class TestCheckEnviron(unittest.TestCase):
'wsgi.run_once': None,
'wsgi.url_scheme': 'http',
'PATH_INFO': path,
- 'QUERY_STRING': str(''),
+ 'QUERY_STRING': '',
}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
@@ -265,7 +242,7 @@ class TestCheckEnviron(unittest.TestCase):
class TestIteratorWrapper(unittest.TestCase):
def test_close(self):
- class MockIterator(object):
+ class MockIterator:
def __init__(self):
self.closed = False
@@ -296,7 +273,7 @@ class TestWriteWrapper(unittest.TestCase):
self.assertRaises(AssertionError, write_wrapper, 'not a binary')
def test_normal(self):
- class MockWriter(object):
+ class MockWriter:
def __init__(self):
self.written = []
@@ -319,7 +296,7 @@ class TestErrorWrapper(unittest.TestCase):
error_wrapper = ErrorWrapper(None)
self.assertRaises(AssertionError, error_wrapper.close)
- class FakeError(object):
+ class FakeError:
def __init__(self):
self.written = []
self.flushed = False
diff --git a/tests/test_response.py b/tests/test_response.py
index f3dad7f..852bae5 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -1,6 +1,3 @@
-#coding: utf-8
-from __future__ import unicode_literals
-
import sys
@@ -8,7 +5,6 @@ import webtest
from webtest.debugapp import debug_app
from webob import Request
from webob.response import gzip_app_iter
-from webtest.compat import PY3
from tests.compat import unittest
@@ -110,11 +106,11 @@ def links_app(environ, start_response):
body = responses[req.path_info]
body = body.encode('utf8')
headers = [
- ('Content-Type', str('text/html')),
+ ('Content-Type', 'text/html'),
('Content-Length', str(len(body)))
]
if req.path_info in utf8_paths:
- headers[0] = ('Content-Type', str('text/html; charset=utf-8'))
+ headers[0] = ('Content-Type', 'text/html; charset=utf-8')
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
start_response(str(status), headers)
@@ -125,8 +121,8 @@ def gzipped_app(environ, start_response):
status = "200 OK"
encoded_body = list(gzip_app_iter([b'test']))
headers = [
- ('Content-Type', str('text/html')),
- ('Content-Encoding', str('gzip')),
+ ('Content-Type', 'text/html'),
+ ('Content-Encoding', 'gzip'),
]
# PEP 3333 requires native strings:
headers = [(str(k), str(v)) for k, v in headers]
@@ -232,12 +228,6 @@ class TestResponse(unittest.TestCase):
app = webtest.TestApp(links_app, use_unicode=False)
resp = app.get('/utf8/')
self.assertEqual(resp.charset, 'utf-8')
- if not PY3:
- # No need to deal with that in Py3
- self.assertIn("Тестовая страница".encode('utf8'), resp)
- self.assertIn("Тестовая страница", resp, resp)
- target = 'Менделеев'.encode('utf8')
- self.assertIn('This is foo.', resp.click(target, verbose=True))
def test_click_u(self):
app = webtest.TestApp(links_app)
@@ -391,8 +381,6 @@ class TestResponse(unittest.TestCase):
app = webtest.TestApp(links_app)
resp = app.get('/')
- if not PY3:
- unicode(resp)
print(resp.__unicode__())
@@ -412,7 +400,7 @@ class TestFollow(unittest.TestCase):
locations = ['/'] * count
def app(environ, start_response):
- headers = [('Content-Type', str('text/html'))]
+ headers = [('Content-Type', 'text/html')]
if remaining_redirects[0] == 0:
status = "200 OK"
diff --git a/tests/test_sel.py b/tests/test_sel.py
index 65f12b8..228a45d 100644
--- a/tests/test_sel.py
+++ b/tests/test_sel.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
from .compat import unittest
from webtest import sel
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 9916992..7bf54ff 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-
-from __future__ import unicode_literals
import re
import json
import sys
@@ -80,7 +77,7 @@ class stringifyTest(unittest.TestCase):
class json_methodTest(unittest.TestCase):
- class MockTestApp(object):
+ class MockTestApp:
"""Mock TestApp used to test the json_object decorator."""
from webtest.utils import json_method
JSONEncoder = json.JSONEncoder
diff --git a/tox.ini b/tox.ini
index d33bfb0..82fabb1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,6 +1,6 @@
[tox]
skip_missing_interpreters=true
-envlist=py27,py35,py36,py37,py38,coverage,docs
+envlist=py36,py37,py38,coverage,docs
[testenv]
skip_install=true
diff --git a/webtest/app.py b/webtest/app.py
index ccf5c5c..f5cd41b 100644
--- a/webtest/app.py
+++ b/webtest/app.py
@@ -7,7 +7,6 @@ Routines for testing WSGI applications.
Most interesting is TestApp
"""
-from __future__ import unicode_literals
import os
import re
@@ -17,13 +16,8 @@ import fnmatch
import mimetypes
from base64 import b64encode
-
-from six import StringIO
-from six import BytesIO
-from six import string_types
-from six import binary_type
-from six import text_type
-from six.moves import http_cookiejar
+from http import cookiejar as http_cookiejar
+from io import BytesIO, StringIO
from webtest.compat import urlparse
from webtest.compat import to_bytes
@@ -42,18 +36,18 @@ __all__ = ['TestApp', 'TestRequest']
class AppError(Exception):
def __init__(self, message, *args):
- if isinstance(message, binary_type):
+ if isinstance(message, bytes):
message = message.decode('utf8')
str_args = ()
for arg in args:
if isinstance(arg, webob.Response):
body = arg.body
- if isinstance(body, binary_type):
+ if isinstance(body, bytes):
if arg.charset:
arg = body.decode(arg.charset)
else:
arg = repr(body)
- elif isinstance(arg, binary_type):
+ elif isinstance(arg, bytes):
try:
arg = arg.decode('utf8')
except UnicodeDecodeError:
@@ -85,7 +79,7 @@ class TestRequest(webob.BaseRequest):
ResponseClass = TestResponse
-class TestApp(object):
+class TestApp:
"""
Wraps a WSGI application in a more convenient interface for
testing. It uses extended version of :class:`webob.BaseRequest`
@@ -150,15 +144,15 @@ class TestApp(object):
if 'WEBTEST_TARGET_URL' in os.environ:
app = os.environ['WEBTEST_TARGET_URL']
- if isinstance(app, string_types):
+ if isinstance(app, str):
if app.startswith('http'):
try:
from wsgiproxy import HostProxy
except ImportError: # pragma: no cover
- raise ImportError((
+ raise ImportError(
'Using webtest with a real url requires WSGIProxy2. '
'Please install it with: '
- 'pip install WSGIProxy2'))
+ 'pip install WSGIProxy2')
if '#' not in app:
app += '#httplib'
url, client = app.split('#', 1)
@@ -212,7 +206,7 @@ class TestApp(object):
val = b64encode(to_bytes(val)).strip()
val = val.decode('latin1')
elif authtype in ('Bearer', 'JWT') and val and \
- isinstance(val, (str, text_type)):
+ isinstance(val, (str, str)):
val = val.strip()
else:
raise ValueError(invalid_value)
@@ -230,7 +224,7 @@ class TestApp(object):
@property
def cookies(self):
- return dict([(cookie.name, cookie.value) for cookie in self.cookiejar])
+ return {cookie.name: cookie.value for cookie in self.cookiejar}
def set_cookie(self, name, value):
"""
@@ -318,10 +312,10 @@ class TestApp(object):
url = self._remove_fragment(url)
if params:
url = utils.build_params(url, params)
- if str('?') in url:
- url, environ['QUERY_STRING'] = url.split(str('?'), 1)
+ if '?' in url:
+ url, environ['QUERY_STRING'] = url.split('?', 1)
else:
- environ['QUERY_STRING'] = str('')
+ environ['QUERY_STRING'] = ''
req = self.RequestClass.blank(url, environ)
if xhr:
headers = self._add_xhr_header(headers)
@@ -479,12 +473,12 @@ class TestApp(object):
def _append_file(file_info):
key, filename, value, fcontent = self._get_file_info(file_info)
- if isinstance(key, text_type):
+ if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
raise # file name must be ascii
- if isinstance(filename, text_type):
+ if isinstance(filename, str):
try:
filename = filename.encode('utf8')
except: # pragma: no cover
@@ -500,7 +494,7 @@ class TestApp(object):
b'Content-Type: ' + fcontent, b'', value])
for key, value in params:
- if isinstance(key, text_type):
+ if isinstance(key, str):
try:
key = key.encode('ascii')
except: # pragma: no cover
@@ -522,11 +516,11 @@ class TestApp(object):
else:
if isinstance(value, int):
value = str(value).encode('utf8')
- elif isinstance(value, text_type):
+ elif isinstance(value, str):
value = value.encode('utf8')
elif not isinstance(value, (bytes, str)):
raise ValueError((
- 'Value for field {0} is a {1} ({2}). '
+ 'Value for field {} is a {} ({}). '
'It must be str, bytes or an int'
).format(key, type(value), value))
lines.extend([
@@ -568,12 +562,12 @@ class TestApp(object):
resp = app.do_request(req)
"""
- if isinstance(url_or_req, text_type):
+ if isinstance(url_or_req, str):
url_or_req = str(url_or_req)
for (k, v) in req_params.items():
- if isinstance(v, text_type):
+ if isinstance(v, str):
req_params[k] = str(v)
- if isinstance(url_or_req, string_types):
+ if isinstance(url_or_req, str):
req = self.RequestClass.blank(url_or_req, **req_params)
else:
req = url_or_req.copy()
@@ -662,10 +656,10 @@ class TestApp(object):
if status == '*':
return
res_status = res.status
- if (isinstance(status, string_types) and '*' in status):
+ if (isinstance(status, str) and '*' in status):
if re.match(fnmatch.translate(status), res_status, re.I):
return
- if isinstance(status, string_types):
+ if isinstance(status, str):
if status == res_status:
return
if isinstance(status, (list, tuple)):
@@ -738,7 +732,7 @@ class TestApp(object):
environ['CONTENT_TYPE'] = content_type
elif params:
environ.setdefault('CONTENT_TYPE',
- str('application/x-www-form-urlencoded'))
+ 'application/x-www-form-urlencoded')
if content_type is not None:
environ['CONTENT_TYPE'] = content_type
@@ -746,7 +740,7 @@ class TestApp(object):
url = str(url)
url = self._remove_fragment(url)
req = self.RequestClass.blank(url, environ)
- if isinstance(params, text_type):
+ if isinstance(params, str):
params = params.encode(req.charset or 'utf8')
req.environ['wsgi.input'] = BytesIO(params)
req.content_length = len(params)
@@ -767,9 +761,9 @@ class TestApp(object):
return (file_info[0], filename, content, None)
elif 3 <= len(file_info) <= 4:
content = file_info[2]
- if not isinstance(content, binary_type):
+ if not isinstance(content, bytes):
raise ValueError('File content must be %s not %s'
- % (binary_type, type(content)))
+ % (bytes, type(content)))
if len(file_info) == 3:
return tuple(file_info) + (None,)
else:
@@ -786,5 +780,5 @@ class TestApp(object):
def _add_xhr_header(headers):
headers = headers or {}
# if remove str we will be have an error in lint.middleware
- headers.update({'X-REQUESTED-WITH': str('XMLHttpRequest')})
+ headers.update({'X-REQUESTED-WITH': 'XMLHttpRequest'})
return headers
diff --git a/webtest/compat.py b/webtest/compat.py
index 0e97d0b..aa6e26d 100644
--- a/webtest/compat.py
+++ b/webtest/compat.py
@@ -1,37 +1,24 @@
-# -*- coding: utf-8 -*-
import sys
-import six
-from six import PY3
-from six import text_type
-from six.moves import http_cookies
+from http import cookies
-SimpleCookie = http_cookies.SimpleCookie
-CookieError = http_cookies.CookieError
+SimpleCookie = cookies.SimpleCookie
+CookieError = cookies.CookieError
def to_bytes(value, charset='latin1'):
- if isinstance(value, text_type):
+ if isinstance(value, str):
return value.encode(charset)
return value
-if PY3: # pragma: no cover
- from html.entities import name2codepoint
- from urllib.parse import urlencode
- import urllib.parse as urlparse
- from collections.abc import Iterable # noqa
-else: # pragma: no cover
- from htmlentitydefs import name2codepoint # noqa
- from urllib import urlencode # noqa
- import urlparse # noqa
- from collections import Iterable # noqa
+from html.entities import name2codepoint
+from urllib.parse import urlencode
+import urllib.parse as urlparse
+from collections.abc import Iterable # noqa
def print_stderr(value):
- if not PY3:
- if isinstance(value, text_type):
- value = value.encode('utf8')
- six.print_(value, file=sys.stderr)
+ print(value, file=sys.stderr)
def escape_cookie_value(value):
diff --git a/webtest/debugapp.py b/webtest/debugapp.py
index dd05fbc..b7e8ddc 100644
--- a/webtest/debugapp.py
+++ b/webtest/debugapp.py
@@ -1,13 +1,12 @@
import os
-import six
import webob
__all__ = ['DebugApp', 'make_debug_app']
-class DebugApp(object):
+class DebugApp:
"""The WSGI application used for testing"""
def __init__(self, form=None, show_form=False):
@@ -31,8 +30,6 @@ class DebugApp(object):
if 'errorlog' in req.GET:
log = req.GET['errorlog']
- if not six.PY3 and not isinstance(log, six.binary_type):
- log = log.encode('utf8')
req.environ['wsgi.errors'].write(log)
status = str(req.GET.get('status', '200 OK'))
@@ -42,14 +39,14 @@ class DebugApp(object):
for name, value in sorted(environ.items()):
if name.upper() != name:
value = repr(value)
- parts.append(str('%s: %s\n') % (name, value))
+ parts.append('%s: %s\n' % (name, value))
body = ''.join(parts)
- if not isinstance(body, six.binary_type):
+ if not isinstance(body, bytes):
body = body.encode('latin1')
if req.content_length:
- body += six.b('-- Body ----------\n')
+ body += b'-- Body ----------\n'
body += req.body
else:
body = ''
@@ -60,14 +57,14 @@ class DebugApp(object):
body = ''
headers = [
- ('Content-Type', str('text/plain')),
+ ('Content-Type', 'text/plain'),
('Content-Length', str(len(body)))]
if not self.show_form:
for name, value in req.GET.items():
if name.startswith('header-'):
header_name = name[len('header-'):]
- if isinstance(header_name, six.text_type):
+ if isinstance(header_name, str):
header_name = str(header_name)
header_name = header_name.title()
headers.append((header_name, str(value)))
@@ -76,18 +73,18 @@ class DebugApp(object):
resp.status = status
resp.headers.update(headers)
if req.method != 'HEAD':
- if isinstance(body, six.text_type):
+ if isinstance(body, str):
resp.body = body.encode('utf8')
else:
resp.body = body
return resp(environ, start_response)
-debug_app = DebugApp(form=six.b('''<html><body>
+debug_app = DebugApp(form=b'''<html><body>
<form action="/form-submit" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="Submit!">
-</form></body></html>'''))
+</form></body></html>''')
def make_debug_app(global_conf, **local_conf):
diff --git a/webtest/ext.py b/webtest/ext.py
index 91605c2..e28ae31 100644
--- a/webtest/ext.py
+++ b/webtest/ext.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
__doc__ = 'webtest.ext is now in a separate package name webtest-casperjs'
diff --git a/webtest/forms.py b/webtest/forms.py
index a64050d..d0b8c32 100644
--- a/webtest/forms.py
+++ b/webtest/forms.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""Helpers to fill and submit forms."""
import operator
@@ -10,11 +9,11 @@ from collections import OrderedDict
from webtest import utils
-class NoValue(object):
+class NoValue:
pass
-class Upload(object):
+class Upload:
"""
A file to upload::
@@ -48,7 +47,7 @@ class Upload(object):
return '<Upload "%s">' % self.filename
-class Field(object):
+class Field:
"""Base class for all Field objects.
.. attribute:: classes
@@ -101,7 +100,7 @@ class Select(Field):
"""Field representing ``<select />`` form element."""
def __init__(self, *args, **attrs):
- super(Select, self).__init__(*args, **attrs)
+ super().__init__(*args, **attrs)
self.options = []
self.optionPositions = []
# Undetermined yet:
@@ -170,7 +169,7 @@ class MultipleSelect(Field):
"""Field representing ``<select multiple="multiple">``"""
def __init__(self, *args, **attrs):
- super(MultipleSelect, self).__init__(*args, **attrs)
+ super().__init__(*args, **attrs)
self.options = []
# Undetermined yet:
self.selectedIndices = []
@@ -267,7 +266,7 @@ class Checkbox(Field):
"""
def __init__(self, *args, **attrs):
- super(Checkbox, self).__init__(*args, **attrs)
+ super().__init__(*args, **attrs)
self._checked = 'checked' in attrs
def value__set(self, value):
@@ -369,7 +368,7 @@ Field.classes['textarea'] = Textarea
Field.classes['radio'] = Radio
-class Form(object):
+class Form:
"""This object represents a form that has been found in a page.
:param response: `webob.response.TestResponse` instance
@@ -463,8 +462,8 @@ class Form(object):
# https://github.com/Pylons/webtest/issues/73
if sys.version_info[:2] <= (2, 6):
- attrs = dict((k.encode('utf-8') if isinstance(k, unicode)
- else k, v) for k, v in attrs.items())
+ attrs = {k.encode('utf-8') if isinstance(k, unicode)
+ else k: v for k, v in attrs.items()}
# https://github.com/Pylons/webtest/issues/131
reserved_attributes = ('form', 'tag', 'pos')
@@ -528,7 +527,7 @@ class Form(object):
% (name, ', '.join(map(repr, self.fields.keys()))))
all_checkboxes = all(isinstance(f, Checkbox) for f in fields)
if all_checkboxes and isinstance(value, list):
- values = set(utils.stringify(v) for v in value)
+ values = {utils.stringify(v) for v in value}
for f in fields:
f.checked = f._value in values
else:
diff --git a/webtest/http.py b/webtest/http.py
index 890ef96..efe4ace 100644
--- a/webtest/http.py
+++ b/webtest/http.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
This module contains some helpers to deal with the real http
world.
@@ -11,9 +10,9 @@ import socket
import time
import os
-import six
+from http import client
+
import webob
-from six.moves import http_client
from waitress.server import TcpWSGIServer
@@ -33,11 +32,11 @@ def check_server(host, port, path_info='/', timeout=3, retries=30):
time.sleep(.3)
for i in range(retries):
try:
- conn = http_client.HTTPConnection(host, int(port), timeout=timeout)
+ conn = client.HTTPConnection(host, int(port), timeout=timeout)
conn.request('GET', path_info)
res = conn.getresponse()
return res.status
- except (socket.error, http_client.HTTPException):
+ except (OSError, client.HTTPException):
time.sleep(.3)
return 0
@@ -53,7 +52,7 @@ class StopableWSGIServer(TcpWSGIServer):
was_shutdown = False
def __init__(self, application, *args, **kwargs):
- super(StopableWSGIServer, self).__init__(self.wrapper, *args, **kwargs)
+ super().__init__(self.wrapper, *args, **kwargs)
self.runner = None
self.test_app = application
self.application_url = 'http://%s:%s/' % (self.adj.host, self.adj.port)
@@ -72,8 +71,8 @@ class StopableWSGIServer(TcpWSGIServer):
filename = req.params.get('__file__')
if os.path.isfile(filename):
body = open(filename, 'rb').read()
- body = body.replace(six.b('http://localhost/'),
- six.b('http://%s/' % req.host))
+ body = body.replace(b'http://localhost/',
+ bytes('http://%s/' % req.host, 'UTF-8'))
resp.body = body
else:
resp.status = '404 Not Found'
@@ -86,7 +85,7 @@ class StopableWSGIServer(TcpWSGIServer):
"""Run the server"""
try:
self.asyncore.loop(.5, map=self._map)
- except select.error: # pragma: no cover
+ except OSError: # pragma: no cover
if not self.was_shutdown:
raise
diff --git a/webtest/lint.py b/webtest/lint.py
index 97e35ce..e0e6870 100644
--- a/webtest/lint.py
+++ b/webtest/lint.py
@@ -114,14 +114,9 @@ Some of the things this checks:
is garbage collected).
"""
-from __future__ import unicode_literals
import re
import warnings
-from six import PY3
-from six import binary_type
-from six import string_types
-from six import text_type
from webtest.compat import Iterable
@@ -133,15 +128,15 @@ valid_methods = (
'TRACE', 'PATCH',
)
-METADATA_TYPE = PY3 and (str, binary_type) or (str,)
+METADATA_TYPE = (str, bytes)
# PEP-3333 says that environment variables must be "native strings",
# i.e. str(), which however is something *different* in py2 and py3.
-SLASH = str('/')
+SLASH = '/'
def to_string(value):
- if not isinstance(value, string_types):
+ if not isinstance(value, str):
return value.decode('latin1')
else:
return value
@@ -211,7 +206,7 @@ def middleware(application, global_conf=None):
return lint_app
-class InputWrapper(object):
+class InputWrapper:
def __init__(self, wsgi_input):
self.input = wsgi_input
@@ -219,12 +214,12 @@ class InputWrapper(object):
def read(self, *args):
assert len(args) <= 1
v = self.input.read(*args)
- assert type(v) is binary_type
+ assert type(v) is bytes
return v
def readline(self, *args):
v = self.input.readline(*args)
- assert type(v) is binary_type
+ assert type(v) is bytes
return v
def readlines(self, *args):
@@ -232,7 +227,7 @@ class InputWrapper(object):
lines = self.input.readlines(*args)
assert isinstance(lines, list)
for line in lines:
- assert type(line) is binary_type
+ assert type(line) is bytes
return lines
def __iter__(self):
@@ -249,14 +244,12 @@ class InputWrapper(object):
return self.input.seek(*a, **kw)
-class ErrorWrapper(object):
+class ErrorWrapper:
def __init__(self, wsgi_errors):
self.errors = wsgi_errors
def write(self, s):
- if not PY3:
- assert type(s) is binary_type
self.errors.write(s)
def flush(self):
@@ -270,17 +263,17 @@ class ErrorWrapper(object):
raise AssertionError("errors.close() must not be called")
-class WriteWrapper(object):
+class WriteWrapper:
def __init__(self, wsgi_writer):
self.writer = wsgi_writer
def __call__(self, s):
- assert type(s) is binary_type
+ assert type(s) is bytes
self.writer(s)
-class IteratorWrapper(object):
+class IteratorWrapper:
def __init__(self, wsgi_iterator, check_start_response):
self.original_iterator = wsgi_iterator
@@ -300,9 +293,9 @@ class IteratorWrapper(object):
"The application returns and we started iterating over its"
" body, but start_response has not yet been called")
self.check_start_response = None
- assert isinstance(v, binary_type), (
+ assert isinstance(v, bytes), (
"Iterator %r returned a non-%r object: %r"
- % (self.iterator, binary_type, v))
+ % (self.iterator, bytes, v))
return v
__next__ = next
@@ -457,7 +450,7 @@ def _assert_latin1_str(string, message):
if type(string) is not str:
raise AssertionError(message)
- if type(string) is text_type:
+ if type(string) is str:
try:
string.encode('latin1')
except UnicodeEncodeError:
@@ -560,7 +553,7 @@ def check_exc_info(exc_info):
def check_iterator(iterator):
- valid_type = PY3 and bytes or str
+ valid_type = bytes
# Technically a bytes (str for py2.x) is legal, which is why it's a
# really bad idea, because it may cause the response to be returned
# character-by-character
diff --git a/webtest/response.py b/webtest/response.py
index cdd4af2..76917c7 100644
--- a/webtest/response.py
+++ b/webtest/response.py
@@ -1,18 +1,12 @@
-# -*- coding: utf-8 -*-
import re
from json import loads
from webtest import forms
from webtest import utils
from webtest.compat import print_stderr
-from webtest.compat import PY3
from webtest.compat import urlparse
from webtest.compat import to_bytes
-from six import string_types
-from six import binary_type
-from six import text_type
-
from bs4 import BeautifulSoup
import webob
@@ -72,7 +66,7 @@ class TestResponse(webob.Response):
def _parse_forms(self):
forms_ = self._forms_indexed = {}
- form_texts = [text_type(f) for f in self.html('form')]
+ form_texts = [str(f) for f in self.html('form')]
for i, text in enumerate(form_texts):
form = forms.Form(self, text, self.parser_features)
forms_[i] = form
@@ -269,26 +263,6 @@ class TestResponse(webob.Response):
'Only "get" or "post" are allowed for method (you gave %r)'
% method)
- # encode unicode strings for the outside world
- if not PY3 and getattr(self, '_use_unicode', False):
- def to_str(s):
- if isinstance(s, text_type):
- return s.encode(self.charset)
- return s
-
- href = to_str(href)
-
- if 'params' in args:
- args['params'] = [tuple(map(to_str, p))
- for p in args['params']]
-
- if 'upload_files' in args:
- args['upload_files'] = [map(to_str, f)
- for f in args['upload_files']]
-
- if 'content_type' in args:
- args['content_type'] = to_str(args['content_type'])
-
if method == 'get':
method = self.test_app.get
else:
@@ -315,8 +289,8 @@ class TestResponse(webob.Response):
"""
if not self.charset:
raise AttributeError(
- ("You cannot access Response.unicode_normal_body "
- "unless charset is set"))
+ "You cannot access Response.unicode_normal_body "
+ "unless charset is set")
if getattr(self, '_unicode_normal_body', None) is None:
self._unicode_normal_body = self._unicode_normal_body_regex.sub(
' ', self.testbody)
@@ -328,9 +302,9 @@ class TestResponse(webob.Response):
of the response. Whitespace is normalized when searching
for a string.
"""
- if not self.charset and isinstance(s, text_type):
+ if not self.charset and isinstance(s, str):
s = s.encode('utf8')
- if isinstance(s, binary_type):
+ if isinstance(s, bytes):
return s in self.body or s in self.normal_body
return s in self.testbody or s in self.unicode_normal_body
@@ -350,7 +324,7 @@ class TestResponse(webob.Response):
if 'no' in kw:
no = kw['no']
del kw['no']
- if isinstance(no, string_types):
+ if isinstance(no, str):
no = [no]
else:
no = []
@@ -371,25 +345,21 @@ class TestResponse(webob.Response):
"Body contains bad string %r" % no_s)
def __str__(self):
- simple_body = str('\n').join([l for l in self.testbody.splitlines()
+ simple_body = '\n'.join([l for l in self.testbody.splitlines()
if l.strip()])
headers = [(n.title(), v)
for n, v in self.headerlist
if n.lower() != 'content-length']
headers.sort()
- output = str('Response: %s\n%s\n%s') % (
+ output = 'Response: %s\n%s\n%s' % (
self.status,
- str('\n').join([str('%s: %s') % (n, v) for n, v in headers]),
+ '\n'.join(['%s: %s' % (n, v) for n, v in headers]),
simple_body)
- if not PY3 and isinstance(output, text_type):
- output = output.encode(self.charset or 'utf8', 'replace')
return output
def __unicode__(self):
output = str(self)
- if PY3:
- return output
- return output.decode(self.charset or 'utf8', 'replace')
+ return output
def __repr__(self):
# Specifically intended for doctests
@@ -451,8 +421,8 @@ class TestResponse(webob.Response):
from elementtree import ElementTree # NOQA
except ImportError:
raise ImportError(
- ("You must have ElementTree installed "
- "(or use Python 2.5) to use response.xml"))
+ "You must have ElementTree installed "
+ "(or use Python 2.5) to use response.xml")
# ElementTree can't parse unicode => use `body` instead of `testbody`
return ElementTree.XML(self.body)
@@ -532,10 +502,7 @@ class TestResponse(webob.Response):
name = f.name
f.close()
f = open(name, 'w')
- if PY3:
- f.write(self.body.decode(self.charset or 'ascii', 'replace'))
- else:
- f.write(self.body)
+ f.write(self.body.decode(self.charset or 'ascii', 'replace'))
f.close()
if name[0] != '/': # pragma: no cover
# windows ...
diff --git a/webtest/sel.py b/webtest/sel.py
index c2125f4..d336b1e 100644
--- a/webtest/sel.py
+++ b/webtest/sel.py
@@ -1,8 +1,7 @@
-# -*- coding: utf-8 -*-
__doc__ = 'webtest.sel is now in a separate package name webtest-selenium'
-class SeleniumApp(object):
+class SeleniumApp:
def __init__(self, *args, **kwargs):
raise ImportError(__doc__)
diff --git a/webtest/utils.py b/webtest/utils.py
index be163fb..a5fe3cf 100644
--- a/webtest/utils.py
+++ b/webtest/utils.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import re
import six
from json import dumps
@@ -6,7 +5,7 @@ from json import dumps
from webtest.compat import urlencode
-class NoDefault(object):
+class NoDefault:
"""Sentinel to uniquely represent no default value."""
def __repr__(self):
@@ -48,9 +47,9 @@ def json_method(method):
def stringify(value):
- if isinstance(value, six.text_type):
+ if isinstance(value, str):
return value
- elif isinstance(value, six.binary_type):
+ elif isinstance(value, bytes):
return value.decode('utf8')
else:
return str(value)
@@ -72,7 +71,7 @@ def encode_params(params, content_type):
charset = charset.strip('; ').lower()
encoded_params = []
for k, v in params:
- if isinstance(v, six.text_type):
+ if isinstance(v, str):
v = v.encode(charset)
encoded_params.append((k, v))
params = encoded_params
@@ -81,12 +80,12 @@ def encode_params(params, content_type):
def build_params(url, params):
- if not isinstance(params, six.string_types):
+ if not isinstance(params, str):
params = urlencode(params, doseq=True)
- if str('?') in url:
- url += str('&')
+ if '?' in url:
+ url += '&'
else:
- url += str('?')
+ url += '?'
url += params
return url
@@ -95,9 +94,9 @@ def make_pattern(pat):
"""Find element pattern can be a regex or a callable."""
if pat is None:
return None
- if isinstance(pat, six.binary_type):
+ if isinstance(pat, bytes):
pat = pat.decode('utf8')
- if isinstance(pat, six.text_type):
+ if isinstance(pat, str):
pat = re.compile(pat)
if hasattr(pat, 'search'):
return pat.search
@@ -107,7 +106,7 @@ def make_pattern(pat):
"Cannot make callable pattern object out of %r" % pat)
-class _RequestCookieAdapter(object):
+class _RequestCookieAdapter:
"""
cookielib.CookieJar support for webob.Request
"""
@@ -153,7 +152,7 @@ class _RequestCookieAdapter(object):
return self._request.headers.items()
-class _ResponseCookieAdapter(object):
+class _ResponseCookieAdapter:
"""
cookielib.CookieJar support for webob.Response
"""