summaryrefslogtreecommitdiff
path: root/webtest
diff options
context:
space:
mode:
Diffstat (limited to 'webtest')
-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
10 files changed, 106 insertions, 173 deletions
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
"""