summaryrefslogtreecommitdiff
path: root/dummyserver
diff options
context:
space:
mode:
authorRatan Kulshreshtha <ratan.shreshtha@gmail.com>2019-05-25 03:05:50 +0530
committerRatan Kulshreshtha <ratan.shreshtha@gmail.com>2019-05-25 03:05:50 +0530
commit266b347d393a16684f2b5abb87aeb5b13ca4f0b7 (patch)
treee8a810cfaa647f61027f82175b29cae2ceb2a61e /dummyserver
parent3773cf123cf1e195691f26ad870de8f6b423e7a9 (diff)
downloadurllib3-266b347d393a16684f2b5abb87aeb5b13ca4f0b7.tar.gz
Auto formatting using black
Diffstat (limited to 'dummyserver')
-rw-r--r--dummyserver/handlers.py158
-rwxr-xr-xdummyserver/proxy.py44
-rwxr-xr-xdummyserver/server.py101
-rw-r--r--dummyserver/testcase.py102
4 files changed, 211 insertions, 194 deletions
diff --git a/dummyserver/handlers.py b/dummyserver/handlers.py
index 146241dc..a0db5668 100644
--- a/dummyserver/handlers.py
+++ b/dummyserver/handlers.py
@@ -23,13 +23,13 @@ log = logging.getLogger(__name__)
class Response(object):
- def __init__(self, body='', status='200 OK', headers=None):
+ def __init__(self, body="", status="200 OK", headers=None):
self.body = body
self.status = status
self.headers = headers or [("Content-type", "text/plain")]
def __call__(self, request_handler):
- status, reason = self.status.split(' ', 1)
+ status, reason = self.status.split(" ", 1)
request_handler.set_status(int(status), reason)
for header, value in self.headers:
request_handler.add_header(header, value)
@@ -38,13 +38,13 @@ class Response(object):
if isinstance(self.body, list):
for item in self.body:
if not isinstance(item, bytes):
- item = item.encode('utf8')
+ item = item.encode("utf8")
request_handler.write(item)
request_handler.flush()
else:
body = self.body
if not isinstance(body, bytes):
- body = body.encode('utf8')
+ body = body.encode("utf8")
request_handler.write(body)
@@ -61,6 +61,7 @@ class TestingApp(RequestHandler):
it exists. Status code 200 indicates success, 400 indicates failure. Each
method has its own conditions for success/failure.
"""
+
def get(self):
""" Handle GET requests """
self._call_method()
@@ -89,15 +90,15 @@ class TestingApp(RequestHandler):
req.params[k] = next(iter(v))
path = req.path[:]
- if not path.startswith('/'):
+ if not path.startswith("/"):
path = urlsplit(path).path
- target = path[1:].replace('/', '_')
+ target = path[1:].replace("/", "_")
method = getattr(self, target, self.index)
resp = method(req)
- if dict(resp.headers).get('Connection') == 'close':
+ if dict(resp.headers).get("Connection") == "close":
# FIXME: Can we kill the connection somehow?
pass
@@ -112,8 +113,7 @@ class TestingApp(RequestHandler):
cert = request.get_ssl_certificate()
subject = dict()
if cert is not None:
- subject = dict((k, v) for (k, v) in [y for z in cert['subject']
- for y in z])
+ subject = dict((k, v) for (k, v) in [y for z in cert["subject"] for y in z])
return Response(json.dumps(subject))
def source_address(self, request):
@@ -121,98 +121,104 @@ class TestingApp(RequestHandler):
return Response(request.remote_ip)
def set_up(self, request):
- test_type = request.params.get('test_type')
- test_id = request.params.get('test_id')
+ test_type = request.params.get("test_type")
+ test_id = request.params.get("test_id")
if test_id:
- print('\nNew test %s: %s' % (test_type, test_id))
+ print("\nNew test %s: %s" % (test_type, test_id))
else:
- print('\nNew test %s' % test_type)
+ print("\nNew test %s" % test_type)
return Response("Dummy server is ready!")
def specific_method(self, request):
"Confirm that the request matches the desired method type"
- method = request.params.get('method')
+ method = request.params.get("method")
if method and not isinstance(method, str):
- method = method.decode('utf8')
+ method = method.decode("utf8")
if request.method != method:
- return Response("Wrong method: %s != %s" %
- (method, request.method), status='400 Bad Request')
+ return Response(
+ "Wrong method: %s != %s" % (method, request.method),
+ status="400 Bad Request",
+ )
return Response()
def upload(self, request):
"Confirm that the uploaded file conforms to specification"
# FIXME: This is a huge broken mess
- param = request.params.get('upload_param', b'myfile').decode('ascii')
- filename = request.params.get('upload_filename', b'').decode('utf-8')
- size = int(request.params.get('upload_size', '0'))
+ param = request.params.get("upload_param", b"myfile").decode("ascii")
+ filename = request.params.get("upload_filename", b"").decode("utf-8")
+ size = int(request.params.get("upload_size", "0"))
files_ = request.files.get(param)
if len(files_) != 1:
- return Response("Expected 1 file for '%s', not %d" % (param, len(files_)),
- status='400 Bad Request')
+ return Response(
+ "Expected 1 file for '%s', not %d" % (param, len(files_)),
+ status="400 Bad Request",
+ )
file_ = files_[0]
- data = file_['body']
+ data = file_["body"]
if int(size) != len(data):
- return Response("Wrong size: %d != %d" %
- (size, len(data)), status='400 Bad Request')
+ return Response(
+ "Wrong size: %d != %d" % (size, len(data)), status="400 Bad Request"
+ )
- got_filename = file_['filename']
- if(isinstance(got_filename, binary_type)):
- got_filename = got_filename.decode('utf-8')
+ got_filename = file_["filename"]
+ if isinstance(got_filename, binary_type):
+ got_filename = got_filename.decode("utf-8")
# Tornado can leave the trailing \n in place on the filename.
if filename != got_filename:
return Response(
u"Wrong filename: %s != %s" % (filename, file_.filename),
- status='400 Bad Request')
+ status="400 Bad Request",
+ )
return Response()
def redirect(self, request):
"Perform a redirect to ``target``"
- target = request.params.get('target', '/')
- status = request.params.get('status', '303 See Other')
+ target = request.params.get("target", "/")
+ status = request.params.get("status", "303 See Other")
if len(status) == 3:
- status = '%s Redirect' % status.decode('latin-1')
+ status = "%s Redirect" % status.decode("latin-1")
- headers = [('Location', target)]
+ headers = [("Location", target)]
return Response(status=status, headers=headers)
def not_found(self, request):
- return Response('Not found', status='404 Not Found')
+ return Response("Not found", status="404 Not Found")
def multi_redirect(self, request):
"Performs a redirect chain based on ``redirect_codes``"
- codes = request.params.get('redirect_codes', b'200').decode('utf-8')
- head, tail = codes.split(',', 1) if "," in codes else (codes, None)
+ codes = request.params.get("redirect_codes", b"200").decode("utf-8")
+ head, tail = codes.split(",", 1) if "," in codes else (codes, None)
status = "{0} {1}".format(head, responses[int(head)])
if not tail:
return Response("Done redirecting", status=status)
- headers = [('Location', '/multi_redirect?redirect_codes=%s' % tail)]
+ headers = [("Location", "/multi_redirect?redirect_codes=%s" % tail)]
return Response(status=status, headers=headers)
def keepalive(self, request):
- if request.params.get('close', b'0') == b'1':
- headers = [('Connection', 'close')]
- return Response('Closing', headers=headers)
+ if request.params.get("close", b"0") == b"1":
+ headers = [("Connection", "close")]
+ return Response("Closing", headers=headers)
- headers = [('Connection', 'keep-alive')]
- return Response('Keeping alive', headers=headers)
+ headers = [("Connection", "keep-alive")]
+ return Response("Keeping alive", headers=headers)
def sleep(self, request):
"Sleep for a specified amount of ``seconds``"
# DO NOT USE THIS, IT'S DEPRECATED.
# FIXME: Delete this once appengine tests are fixed to not use this handler.
- seconds = float(request.params.get('seconds', '1'))
+ seconds = float(request.params.get("seconds", "1"))
time.sleep(seconds)
return Response()
def echo(self, request):
"Echo back the params"
- if request.method == 'GET':
+ if request.method == "GET":
return Response(request.query)
return Response(request.body)
@@ -220,23 +226,25 @@ class TestingApp(RequestHandler):
def encodingrequest(self, request):
"Check for UA accepting gzip/deflate encoding"
data = b"hello, world!"
- encoding = request.headers.get('Accept-Encoding', '')
+ encoding = request.headers.get("Accept-Encoding", "")
headers = None
- if encoding == 'gzip':
- headers = [('Content-Encoding', 'gzip')]
+ if encoding == "gzip":
+ headers = [("Content-Encoding", "gzip")]
file_ = BytesIO()
- with contextlib.closing(gzip.GzipFile('', mode='w', fileobj=file_)) as zipfile:
+ with contextlib.closing(
+ gzip.GzipFile("", mode="w", fileobj=file_)
+ ) as zipfile:
zipfile.write(data)
data = file_.getvalue()
- elif encoding == 'deflate':
- headers = [('Content-Encoding', 'deflate')]
+ elif encoding == "deflate":
+ headers = [("Content-Encoding", "deflate")]
data = zlib.compress(data)
- elif encoding == 'garbage-gzip':
- headers = [('Content-Encoding', 'gzip')]
- data = 'garbage'
- elif encoding == 'garbage-deflate':
- headers = [('Content-Encoding', 'deflate')]
- data = 'garbage'
+ elif encoding == "garbage-gzip":
+ headers = [("Content-Encoding", "gzip")]
+ data = "garbage"
+ elif encoding == "garbage-deflate":
+ headers = [("Content-Encoding", "deflate")]
+ data = "garbage"
return Response(data, headers=headers)
def headers(self, request):
@@ -247,10 +255,9 @@ class TestingApp(RequestHandler):
It's not currently very flexible as the number of retries is hard-coded.
"""
- test_name = request.headers.get('test-name', None)
+ test_name = request.headers.get("test-name", None)
if not test_name:
- return Response("test-name header not set",
- status="400 Bad Request")
+ return Response("test-name header not set", status="400 Bad Request")
RETRY_TEST_NAMES[test_name] += 1
@@ -260,25 +267,23 @@ class TestingApp(RequestHandler):
return Response("need to keep retrying!", status="418 I'm A Teapot")
def chunked(self, request):
- return Response(['123'] * 4)
+ return Response(["123"] * 4)
def chunked_gzip(self, request):
chunks = []
compressor = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS)
- for uncompressed in [b'123'] * 4:
+ for uncompressed in [b"123"] * 4:
chunks.append(compressor.compress(uncompressed))
chunks.append(compressor.flush())
- return Response(chunks, headers=[('Content-Encoding', 'gzip')])
+ return Response(chunks, headers=[("Content-Encoding", "gzip")])
def nbytes(self, request):
- length = int(request.params.get('length'))
- data = b'1' * length
- return Response(
- data,
- headers=[('Content-Type', 'application/octet-stream')])
+ length = int(request.params.get("length"))
+ data = b"1" * length
+ return Response(data, headers=[("Content-Type", "application/octet-stream")])
def status(self, request):
status = request.params.get("status", "200 OK")
@@ -289,8 +294,8 @@ class TestingApp(RequestHandler):
if datetime.now() - self.application.last_req < timedelta(seconds=1):
status = request.params.get("status", b"429 Too Many Requests")
return Response(
- status=status.decode('utf-8'),
- headers=[('Retry-After', '1')])
+ status=status.decode("utf-8"), headers=[("Retry-After", "1")]
+ )
self.application.last_req = datetime.now()
@@ -298,15 +303,16 @@ class TestingApp(RequestHandler):
def redirect_after(self, request):
"Perform a redirect to ``target``"
- date = request.params.get('date')
+ date = request.params.get("date")
if date:
- retry_after = str(httputil.format_timestamp(
- datetime.fromtimestamp(float(date))))
+ retry_after = str(
+ httputil.format_timestamp(datetime.fromtimestamp(float(date)))
+ )
else:
- retry_after = '1'
- target = request.params.get('target', '/')
- headers = [('Location', target), ('Retry-After', retry_after)]
- return Response(status='303 See Other', headers=headers)
+ retry_after = "1"
+ target = request.params.get("target", "/")
+ headers = [("Location", target), ("Retry-After", retry_after)]
+ return Response(status="303 See Other", headers=headers)
def shutdown(self, request):
sys.exit()
diff --git a/dummyserver/proxy.py b/dummyserver/proxy.py
index 907dd074..7429d441 100755
--- a/dummyserver/proxy.py
+++ b/dummyserver/proxy.py
@@ -34,25 +34,30 @@ import tornado.iostream
import tornado.web
import tornado.httpclient
-__all__ = ['ProxyHandler', 'run_proxy']
+__all__ = ["ProxyHandler", "run_proxy"]
class ProxyHandler(tornado.web.RequestHandler):
- SUPPORTED_METHODS = ['GET', 'POST', 'CONNECT']
+ SUPPORTED_METHODS = ["GET", "POST", "CONNECT"]
@tornado.web.asynchronous
def get(self):
-
def handle_response(response):
- if response.error and not isinstance(response.error,
- tornado.httpclient.HTTPError):
+ if response.error and not isinstance(
+ response.error, tornado.httpclient.HTTPError
+ ):
self.set_status(500)
- self.write('Internal server error:\n' + str(response.error))
+ self.write("Internal server error:\n" + str(response.error))
self.finish()
else:
self.set_status(response.code)
- for header in ('Date', 'Cache-Control', 'Server',
- 'Content-Type', 'Location'):
+ for header in (
+ "Date",
+ "Cache-Control",
+ "Server",
+ "Content-Type",
+ "Location",
+ ):
v = response.headers.get(header)
if v:
self.set_header(header, v)
@@ -62,19 +67,22 @@ class ProxyHandler(tornado.web.RequestHandler):
req = tornado.httpclient.HTTPRequest(
url=self.request.uri,
- method=self.request.method, body=self.request.body,
- headers=self.request.headers, follow_redirects=False,
- allow_nonstandard_methods=True)
+ method=self.request.method,
+ body=self.request.body,
+ headers=self.request.headers,
+ follow_redirects=False,
+ allow_nonstandard_methods=True,
+ )
client = tornado.httpclient.AsyncHTTPClient()
try:
client.fetch(req, handle_response)
except tornado.httpclient.HTTPError as e:
- if hasattr(e, 'response') and e.response:
+ if hasattr(e, "response") and e.response:
self.handle_response(e.response)
else:
self.set_status(500)
- self.write('Internal server error:\n' + str(e))
+ self.write("Internal server error:\n" + str(e))
self.finish()
@tornado.web.asynchronous
@@ -83,7 +91,7 @@ class ProxyHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def connect(self):
- host, port = self.request.uri.split(':')
+ host, port = self.request.uri.split(":")
client = self.request.connection.stream
def read_from_client(data):
@@ -109,7 +117,7 @@ class ProxyHandler(tornado.web.RequestHandler):
def start_tunnel():
client.read_until_close(client_close, read_from_client)
upstream.read_until_close(upstream_close, read_from_upstream)
- client.write(b'HTTP/1.0 200 Connection established\r\n\r\n')
+ client.write(b"HTTP/1.0 200 Connection established\r\n\r\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
upstream = tornado.iostream.IOStream(s)
@@ -121,16 +129,14 @@ def run_proxy(port, start_ioloop=True):
Run proxy on the specified port. If start_ioloop is True (default),
the tornado IOLoop will be started immediately.
"""
- app = tornado.web.Application([
- (r'.*', ProxyHandler),
- ])
+ app = tornado.web.Application([(r".*", ProxyHandler)])
app.listen(port)
ioloop = tornado.ioloop.IOLoop.instance()
if start_ioloop:
ioloop.start()
-if __name__ == '__main__':
+if __name__ == "__main__":
port = 8888
if len(sys.argv) > 1:
port = int(sys.argv[1])
diff --git a/dummyserver/server.py b/dummyserver/server.py
index 8f0794f9..1f899269 100755
--- a/dummyserver/server.py
+++ b/dummyserver/server.py
@@ -27,50 +27,54 @@ import tornado.web
log = logging.getLogger(__name__)
-CERTS_PATH = os.path.join(os.path.dirname(__file__), 'certs')
+CERTS_PATH = os.path.join(os.path.dirname(__file__), "certs")
DEFAULT_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'server.crt'),
- 'keyfile': os.path.join(CERTS_PATH, 'server.key'),
- 'cert_reqs': ssl.CERT_OPTIONAL,
- 'ca_certs': os.path.join(CERTS_PATH, 'cacert.pem'),
+ "certfile": os.path.join(CERTS_PATH, "server.crt"),
+ "keyfile": os.path.join(CERTS_PATH, "server.key"),
+ "cert_reqs": ssl.CERT_OPTIONAL,
+ "ca_certs": os.path.join(CERTS_PATH, "cacert.pem"),
}
DEFAULT_CLIENT_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'client_intermediate.pem'),
- 'keyfile': os.path.join(CERTS_PATH, 'client_intermediate.key'),
- 'subject': dict(countryName=u'FI', stateOrProvinceName=u'dummy',
- organizationName=u'dummy', organizationalUnitName=u'dummy',
- commonName=u'SnakeOilClient',
- emailAddress=u'dummy@test.local'),
+ "certfile": os.path.join(CERTS_PATH, "client_intermediate.pem"),
+ "keyfile": os.path.join(CERTS_PATH, "client_intermediate.key"),
+ "subject": dict(
+ countryName=u"FI",
+ stateOrProvinceName=u"dummy",
+ organizationName=u"dummy",
+ organizationalUnitName=u"dummy",
+ commonName=u"SnakeOilClient",
+ emailAddress=u"dummy@test.local",
+ ),
}
DEFAULT_CLIENT_NO_INTERMEDIATE_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'client_no_intermediate.pem'),
- 'keyfile': os.path.join(CERTS_PATH, 'client_intermediate.key'),
+ "certfile": os.path.join(CERTS_PATH, "client_no_intermediate.pem"),
+ "keyfile": os.path.join(CERTS_PATH, "client_intermediate.key"),
}
-PASSWORD_KEYFILE = os.path.join(CERTS_PATH, 'server_password.key')
-PASSWORD_CLIENT_KEYFILE = os.path.join(CERTS_PATH, 'client_password.key')
+PASSWORD_KEYFILE = os.path.join(CERTS_PATH, "server_password.key")
+PASSWORD_CLIENT_KEYFILE = os.path.join(CERTS_PATH, "client_password.key")
NO_SAN_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'server.no_san.crt'),
- 'keyfile': DEFAULT_CERTS['keyfile']
+ "certfile": os.path.join(CERTS_PATH, "server.no_san.crt"),
+ "keyfile": DEFAULT_CERTS["keyfile"],
}
IP_SAN_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'server.ip_san.crt'),
- 'keyfile': DEFAULT_CERTS['keyfile']
+ "certfile": os.path.join(CERTS_PATH, "server.ip_san.crt"),
+ "keyfile": DEFAULT_CERTS["keyfile"],
}
IPV6_ADDR_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'server.ipv6addr.crt'),
- 'keyfile': os.path.join(CERTS_PATH, 'server.ipv6addr.key'),
+ "certfile": os.path.join(CERTS_PATH, "server.ipv6addr.crt"),
+ "keyfile": os.path.join(CERTS_PATH, "server.ipv6addr.key"),
}
IPV6_SAN_CERTS = {
- 'certfile': os.path.join(CERTS_PATH, 'server.ipv6_san.crt'),
- 'keyfile': DEFAULT_CERTS['keyfile']
+ "certfile": os.path.join(CERTS_PATH, "server.ipv6_san.crt"),
+ "keyfile": DEFAULT_CERTS["keyfile"],
}
-DEFAULT_CA = os.path.join(CERTS_PATH, 'cacert.pem')
-DEFAULT_CA_BAD = os.path.join(CERTS_PATH, 'client_bad.pem')
-NO_SAN_CA = os.path.join(CERTS_PATH, 'cacert.no_san.pem')
-DEFAULT_CA_DIR = os.path.join(CERTS_PATH, 'ca_path_test')
-IPV6_ADDR_CA = os.path.join(CERTS_PATH, 'server.ipv6addr.crt')
-IPV6_SAN_CA = os.path.join(CERTS_PATH, 'server.ipv6_san.crt')
-COMBINED_CERT_AND_KEY = os.path.join(CERTS_PATH, 'server.combined.pem')
+DEFAULT_CA = os.path.join(CERTS_PATH, "cacert.pem")
+DEFAULT_CA_BAD = os.path.join(CERTS_PATH, "client_bad.pem")
+NO_SAN_CA = os.path.join(CERTS_PATH, "cacert.no_san.pem")
+DEFAULT_CA_DIR = os.path.join(CERTS_PATH, "ca_path_test")
+IPV6_ADDR_CA = os.path.join(CERTS_PATH, "server.ipv6addr.crt")
+IPV6_SAN_CA = os.path.join(CERTS_PATH, "server.ipv6_san.crt")
+COMBINED_CERT_AND_KEY = os.path.join(CERTS_PATH, "server.combined.pem")
def _has_ipv6(host):
@@ -100,8 +104,8 @@ def _has_ipv6(host):
# properly. We can not count that localhost will resolve to ::1 on all
# systems. See https://github.com/shazow/urllib3/pull/611 and
# https://bugs.python.org/issue18792
-HAS_IPV6_AND_DNS = _has_ipv6('localhost')
-HAS_IPV6 = _has_ipv6('::1')
+HAS_IPV6_AND_DNS = _has_ipv6("localhost")
+HAS_IPV6 = _has_ipv6("::1")
# Different types of servers we have:
@@ -119,10 +123,10 @@ class SocketServerThread(threading.Thread):
:param ready_event: Event which gets set when the socket handler is
ready to receive requests.
"""
+
USE_IPV6 = HAS_IPV6_AND_DNS
- def __init__(self, socket_handler, host='localhost', port=8081,
- ready_event=None):
+ def __init__(self, socket_handler, host="localhost", port=8081, ready_event=None):
threading.Thread.__init__(self)
self.daemon = True
@@ -134,10 +138,9 @@ class SocketServerThread(threading.Thread):
if self.USE_IPV6:
sock = socket.socket(socket.AF_INET6)
else:
- warnings.warn("No IPv6 support. Falling back to IPv4.",
- NoIPv6Warning)
+ warnings.warn("No IPv6 support. Falling back to IPv4.", NoIPv6Warning)
sock = socket.socket(socket.AF_INET)
- if sys.platform != 'win32':
+ if sys.platform != "win32":
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.host, 0))
self.port = sock.getsockname()[1]
@@ -160,8 +163,8 @@ class SocketServerThread(threading.Thread):
# `tornado.netutil.bind_sockets` again.
# https://github.com/facebook/tornado/pull/977
-def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,
- flags=None):
+
+def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None):
"""Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if
@@ -194,8 +197,9 @@ def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,
if flags is None:
flags = socket.AI_PASSIVE
binded_port = None
- for res in set(socket.getaddrinfo(address, port, family,
- socket.SOCK_STREAM, 0, flags)):
+ for res in set(
+ socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags)
+ ):
af, socktype, proto, canonname, sockaddr = res
try:
sock = socket.socket(af, socktype, proto)
@@ -204,7 +208,7 @@ def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,
continue
raise
set_close_exec(sock.fileno())
- if os.name != 'nt':
+ if os.name != "nt":
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if af == socket.AF_INET6:
# On linux, ipv6 sockets accept ipv4 too by default,
@@ -239,7 +243,7 @@ def run_tornado_app(app, io_loop, certs, scheme, host):
# just construct the datetime object directly.
app.last_req = datetime(1970, 1, 1)
- if scheme == 'https':
+ if scheme == "https":
http_server = tornado.httpserver.HTTPServer(app, ssl_options=certs)
else:
http_server = tornado.httpserver.HTTPServer(app)
@@ -258,8 +262,7 @@ def run_loop_in_thread(io_loop):
def get_unreachable_address():
while True:
- host = ''.join(random.choice(string.ascii_lowercase)
- for _ in range(60))
+ host = "".join(random.choice(string.ascii_lowercase) for _ in range(60))
sockaddr = (host, 54321)
# check if we are really "lucky" and hit an actual server
@@ -271,15 +274,15 @@ def get_unreachable_address():
s.close()
-if __name__ == '__main__':
+if __name__ == "__main__":
# For debugging dummyserver itself - python -m dummyserver.server
from .testcase import TestingApp
- host = '127.0.0.1'
+
+ host = "127.0.0.1"
io_loop = tornado.ioloop.IOLoop.current()
app = tornado.web.Application([(r".*", TestingApp)])
- server, port = run_tornado_app(app, io_loop, None,
- 'http', host)
+ server, port = run_tornado_app(app, io_loop, None, "http", host)
server_thread = run_loop_in_thread(io_loop)
print("Listening on http://{host}:{port}".format(host=host, port=port))
diff --git a/dummyserver/testcase.py b/dummyserver/testcase.py
index ebd0bcb8..bb2d67b0 100644
--- a/dummyserver/testcase.py
+++ b/dummyserver/testcase.py
@@ -16,7 +16,7 @@ from dummyserver.proxy import ProxyHandler
def consume_socket(sock, chunks=65536):
- while not sock.recv(chunks).endswith(b'\r\n\r\n'):
+ while not sock.recv(chunks).endswith(b"\r\n\r\n"):
pass
@@ -25,15 +25,16 @@ class SocketDummyServerTestCase(unittest.TestCase):
A simple socket-based server is created for this class that is good for
exactly one request.
"""
- scheme = 'http'
- host = 'localhost'
+
+ scheme = "http"
+ host = "localhost"
@classmethod
def _start_server(cls, socket_handler):
ready_event = threading.Event()
- cls.server_thread = SocketServerThread(socket_handler=socket_handler,
- ready_event=ready_event,
- host=cls.host)
+ cls.server_thread = SocketServerThread(
+ socket_handler=socket_handler, ready_event=ready_event, host=cls.host
+ )
cls.server_thread.start()
ready_event.wait(5)
if not ready_event.is_set():
@@ -62,27 +63,23 @@ class SocketDummyServerTestCase(unittest.TestCase):
@classmethod
def start_basic_handler(cls, **kw):
return cls.start_response_handler(
- b'HTTP/1.1 200 OK\r\n'
- b'Content-Length: 0\r\n'
- b'\r\n', **kw)
+ b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n" b"\r\n", **kw
+ )
@classmethod
def tearDownClass(cls):
- if hasattr(cls, 'server_thread'):
+ if hasattr(cls, "server_thread"):
cls.server_thread.join(0.1)
def assert_header_received(
- self,
- received_headers,
- header_name,
- expected_value=None
+ self, received_headers, header_name, expected_value=None
):
- header_name = header_name.encode('ascii')
+ header_name = header_name.encode("ascii")
if expected_value is not None:
- expected_value = expected_value.encode('ascii')
+ expected_value = expected_value.encode("ascii")
header_titles = []
for header in received_headers:
- key, value = header.split(b': ')
+ key, value = header.split(b": ")
header_titles.append(key)
if key == header_name and expected_value is not None:
self.assertEqual(value, expected_value)
@@ -93,9 +90,9 @@ class IPV4SocketDummyServerTestCase(SocketDummyServerTestCase):
@classmethod
def _start_server(cls, socket_handler):
ready_event = threading.Event()
- cls.server_thread = SocketServerThread(socket_handler=socket_handler,
- ready_event=ready_event,
- host=cls.host)
+ cls.server_thread = SocketServerThread(
+ socket_handler=socket_handler, ready_event=ready_event, host=cls.host
+ )
cls.server_thread.USE_IPV6 = False
cls.server_thread.start()
ready_event.wait(5)
@@ -112,17 +109,19 @@ class HTTPDummyServerTestCase(unittest.TestCase):
complete. For examples of what test requests you can send to the server,
see the TestingApp in dummyserver/handlers.py.
"""
- scheme = 'http'
- host = 'localhost'
- host_alt = '127.0.0.1' # Some tests need two hosts
+
+ scheme = "http"
+ host = "localhost"
+ host_alt = "127.0.0.1" # Some tests need two hosts
certs = DEFAULT_CERTS
@classmethod
def _start_server(cls):
cls.io_loop = ioloop.IOLoop.current()
app = web.Application([(r".*", TestingApp)])
- cls.server, cls.port = run_tornado_app(app, cls.io_loop, cls.certs,
- cls.scheme, cls.host)
+ cls.server, cls.port = run_tornado_app(
+ app, cls.io_loop, cls.certs, cls.scheme, cls.host
+ )
cls.server_thread = run_loop_in_thread(cls.io_loop)
@classmethod
@@ -141,43 +140,46 @@ class HTTPDummyServerTestCase(unittest.TestCase):
class HTTPSDummyServerTestCase(HTTPDummyServerTestCase):
- scheme = 'https'
- host = 'localhost'
+ scheme = "https"
+ host = "localhost"
certs = DEFAULT_CERTS
-@pytest.mark.skipif(not HAS_IPV6, reason='IPv6 not available')
+@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available")
class IPV6HTTPSDummyServerTestCase(HTTPSDummyServerTestCase):
- host = '::1'
+ host = "::1"
class HTTPDummyProxyTestCase(unittest.TestCase):
- http_host = 'localhost'
- http_host_alt = '127.0.0.1'
+ http_host = "localhost"
+ http_host_alt = "127.0.0.1"
- https_host = 'localhost'
- https_host_alt = '127.0.0.1'
+ https_host = "localhost"
+ https_host_alt = "127.0.0.1"
https_certs = DEFAULT_CERTS
- proxy_host = 'localhost'
- proxy_host_alt = '127.0.0.1'
+ proxy_host = "localhost"
+ proxy_host_alt = "127.0.0.1"
@classmethod
def setUpClass(cls):
cls.io_loop = ioloop.IOLoop.current()
- app = web.Application([(r'.*', TestingApp)])
+ app = web.Application([(r".*", TestingApp)])
cls.http_server, cls.http_port = run_tornado_app(
- app, cls.io_loop, None, 'http', cls.http_host)
+ app, cls.io_loop, None, "http", cls.http_host
+ )
- app = web.Application([(r'.*', TestingApp)])
+ app = web.Application([(r".*", TestingApp)])
cls.https_server, cls.https_port = run_tornado_app(
- app, cls.io_loop, cls.https_certs, 'https', cls.http_host)
+ app, cls.io_loop, cls.https_certs, "https", cls.http_host
+ )
- app = web.Application([(r'.*', ProxyHandler)])
+ app = web.Application([(r".*", ProxyHandler)])
cls.proxy_server, cls.proxy_port = run_tornado_app(
- app, cls.io_loop, None, 'http', cls.proxy_host)
+ app, cls.io_loop, None, "http", cls.proxy_host
+ )
cls.server_thread = run_loop_in_thread(cls.io_loop)
@@ -190,20 +192,20 @@ class HTTPDummyProxyTestCase(unittest.TestCase):
cls.server_thread.join()
-@pytest.mark.skipif(not HAS_IPV6, reason='IPv6 not available')
+@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available")
class IPv6HTTPDummyServerTestCase(HTTPDummyServerTestCase):
- host = '::1'
+ host = "::1"
-@pytest.mark.skipif(not HAS_IPV6, reason='IPv6 not available')
+@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available")
class IPv6HTTPDummyProxyTestCase(HTTPDummyProxyTestCase):
- http_host = 'localhost'
- http_host_alt = '127.0.0.1'
+ http_host = "localhost"
+ http_host_alt = "127.0.0.1"
- https_host = 'localhost'
- https_host_alt = '127.0.0.1'
+ https_host = "localhost"
+ https_host_alt = "127.0.0.1"
https_certs = DEFAULT_CERTS
- proxy_host = '::1'
- proxy_host_alt = '127.0.0.1'
+ proxy_host = "::1"
+ proxy_host_alt = "127.0.0.1"