Repository: abhinavsingh/proxy.py
Pull request #103 (2019-09-27 21:25:34)

Bump develop version to 1.0.1 and Autopep8


Patch:
diff --git a/Makefile b/Makefile
index 0ff3f2f..d6dfe5a 100644
--- a/Makefile
+++ b/Makefile
@@ -23,7 +23,7 @@ clean:
 	find . -name '*.pyo' -exec rm -f {} +
 	find . -name '*~' -exec rm -f {} +
 	rm -f .coverage
-	rm -rf htmlcov dist build
+	rm -rf htmlcov dist build .pytest_cache proxy.py.egg-info
 
 test:
 	python -m unittest tests
diff --git a/plugin_examples.py b/plugin_examples.py
index 17b1207..b40e132 100644
--- a/plugin_examples.py
+++ b/plugin_examples.py
@@ -62,7 +62,8 @@ class ProposedRestApiPlugin(proxy.HttpProxyBasePlugin):
                 self.client.send(proxy.HttpParser.build_response(
                     200, reason=b'OK',
                     headers={b'Content-Type': b'application/json'},
-                    body=proxy.bytes_(json.dumps(self.REST_API_SPEC[self.request.url.path]))
+                    body=proxy.bytes_(json.dumps(
+                        self.REST_API_SPEC[self.request.url.path]))
                 ))
             else:
                 self.client.send(proxy.HttpParser.build_response(
@@ -165,7 +166,8 @@ class ManInTheMiddlePlugin(proxy.HttpProxyBasePlugin):
         pass
 
     def handle_upstream_response(self, raw: bytes) -> bytes:
-        return proxy.HttpParser.build_response(200, reason=b'OK', body=b'Hello from man in the middle')
+        return proxy.HttpParser.build_response(
+            200, reason=b'OK', body=b'Hello from man in the middle')
 
     def on_upstream_connection_close(self) -> None:
         pass
diff --git a/proxy.py b/proxy.py
index ae04cc8..57b06a7 100755
--- a/proxy.py
+++ b/proxy.py
@@ -36,7 +36,7 @@ import select
 if os.name != 'nt':
     import resource
 
-VERSION = (1, 0, 0)
+VERSION = (1, 0, 1)
 __version__ = '.'.join(map(str, VERSION[0:3]))
 __description__ = 'Lightweight, Programmable, TLS interceptor Proxy for HTTP(S), HTTP2, ' \
                   'WebSockets protocols in a single Python file.'
@@ -78,8 +78,10 @@ UNDER_TEST = False
 def text_(s: Any, encoding: str = 'utf-8', errors: str = 'strict') -> Any:
     """Utility to ensure text-like usability.
 
-    If ``s`` is an instance of ``binary_type``, return
-    ``s.decode(encoding, errors)``, otherwise return ``s``"""
+    If s is of type bytes or int, return s.decode(encoding, errors),
+    otherwise return s as it is."""
+    if isinstance(s, int):
+        return str(s)
     if isinstance(s, bytes):
         return s.decode(encoding, errors)
     return s
@@ -88,8 +90,10 @@ def text_(s: Any, encoding: str = 'utf-8', errors: str = 'strict') -> Any:
 def bytes_(s: Any, encoding: str = 'utf-8', errors: str = 'strict') -> Any:
     """Utility to ensure binary-like usability.
 
-    If ``s`` is an instance of ``text_type``, return
-    ``s.encode(encoding, errors)``, otherwise return ``s``"""
+    If s is type str or int, return s.encode(encoding, errors),
+    otherwise return s as it is."""
+    if isinstance(s, int):
+        s = str(s)
     if isinstance(s, str):
         return s.encode(encoding, errors)
     return s
@@ -99,7 +103,8 @@ version = bytes_(__version__)
 CRLF, COLON, WHITESPACE, COMMA, DOT = b'\r\n', b':', b' ', b',', b'.'
 PROXY_AGENT_HEADER_KEY = b'Proxy-agent'
 PROXY_AGENT_HEADER_VALUE = b'proxy.py v' + version
-PROXY_AGENT_HEADER = PROXY_AGENT_HEADER_KEY + COLON + WHITESPACE + PROXY_AGENT_HEADER_VALUE
+PROXY_AGENT_HEADER = PROXY_AGENT_HEADER_KEY + \
+    COLON + WHITESPACE + PROXY_AGENT_HEADER_VALUE
 
 ##
 # Various NamedTuples
@@ -322,7 +327,9 @@ class TcpServer(ABC):
             while self.running:
                 self.run_once()
         except Exception as e:
-            logger.exception('Unexpected error, tearing down server.', exc_info=e)
+            logger.exception(
+                'Unexpected error, tearing down server.',
+                exc_info=e)
         finally:
             self.shutdown()
             logger.info('Closing server socket')
@@ -675,7 +682,8 @@ class HttpParser:
                       body: Optional[bytes] = None) -> bytes:
         if headers is None:
             headers = {}
-        return HttpParser.build_pkt([method, url, protocol_version], headers, body)
+        return HttpParser.build_pkt(
+            [method, url, protocol_version], headers, body)
 
     @staticmethod
     def build_response(status_code: int,
@@ -683,13 +691,14 @@ class HttpParser:
                        reason: Optional[bytes] = None,
                        headers: Optional[Dict[bytes, bytes]] = None,
                        body: Optional[bytes] = None) -> bytes:
-        line = [protocol_version, bytes_(str(status_code))]
+        line = [protocol_version, bytes_(status_code)]
         if reason:
             line.append(reason)
         if headers is None:
             headers = {}
-        if body is not None and not any(k.lower() == b'content-length' for k in headers):
-            headers[b'Content-Length'] = bytes_(str(len(body)))
+        if body is not None and not any(
+                k.lower() == b'content-length' for k in headers):
+            headers[b'Content-Length'] = bytes_(len(body))
         return HttpParser.build_pkt(line, headers, body)
 
     @staticmethod
@@ -762,13 +771,13 @@ class HttpRequestRejected(ProtocolException):
     def response(self, _request: HttpParser) -> Optional[bytes]:
         pkt = []
         if self.status_code is not None:
-            line = b'HTTP/1.1 ' + bytes_(str(self.status_code))
+            line = b'HTTP/1.1 ' + bytes_(self.status_code)
             if self.reason:
                 line += WHITESPACE + self.reason
             pkt.append(line)
             pkt.append(PROXY_AGENT_HEADER)
         if self.body:
-            pkt.append(b'Content-Length: ' + bytes_(str(len(self.body))))
+            pkt.append(b'Content-Length: ' + bytes_(len(self.body)))
             pkt.append(CRLF)
             pkt.append(self.body)
         else:
@@ -1019,7 +1028,8 @@ class HttpProxyPlugin(ProtocolHandlerPlugin):
         w: List[socket.socket] = []
         if self.server and not self.server.closed and self.server.connection:
             r.append(self.server.connection)
-        if self.server and not self.server.closed and self.server.has_buffer() and self.server.connection:
+        if self.server and not self.server.closed and \
+                self.server.has_buffer() and self.server.connection:
             w.append(self.server.connection)
         return r, w, []
 
@@ -1158,8 +1168,8 @@ class HttpProxyPlugin(ProtocolHandlerPlugin):
                             ssl.Purpose.SERVER_AUTH)
                         ctx.options |= ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1
                         self.server._conn = ctx.wrap_socket(
-                            self.server.connection, server_hostname=text_(
-                                self.request.host))
+                            self.server.connection,
+                            server_hostname=text_(self.request.host))
                         logger.info(
                             'TLS interception using %s', generated_cert)
                         return self.client.connection
@@ -1189,7 +1199,8 @@ class HttpProxyPlugin(ProtocolHandlerPlugin):
         if not self.request.has_upstream_server():
             return
 
-        server_host, server_port = self.server.addr if self.server else (None, None)
+        server_host, server_port = self.server.addr if self.server else (
+            None, None)
         if self.request.method == b'CONNECT':
             logger.info(
                 '%s:%s - %s %s:%s - %s bytes' %
@@ -1203,8 +1214,9 @@ class HttpProxyPlugin(ProtocolHandlerPlugin):
         elif self.request.method:
             logger.info(
                 '%s:%s - %s %s:%s%s - %s %s - %s bytes' %
-                (self.client.addr[0], self.client.addr[1], text_(
-                    self.request.method), text_(server_host), server_port,
+                (self.client.addr[0], self.client.addr[1],
+                    text_(self.request.method),
+                    text_(server_host), server_port,
                     text_(self.request.build_url()),
                     text_(self.response.code),
                     text_(self.response.reason),
@@ -1257,7 +1269,8 @@ class HttpWebServerRoutePlugin(ABC):
 
 def route(path: bytes, protocols: Optional[List[int]] = None) -> \
         Callable[[Callable[[HttpParser], bytes]], Type[HttpWebServerRoutePlugin]]:
-    def decorator(func: Callable[[HttpParser], bytes]) -> Type[HttpWebServerRoutePlugin]:
+    def decorator(func: Callable[[HttpParser], bytes]
+                  ) -> Type[HttpWebServerRoutePlugin]:
         class HttpWebServerRouteHandler(HttpWebServerRoutePlugin):
             @staticmethod
             def name() -> str:
@@ -1288,7 +1301,8 @@ class HttpWebServerPacFilePlugin(HttpWebServerRoutePlugin):
 
     def routes(self) -> List[Tuple[int, bytes]]:
         if self.config.pac_file_url_path:
-            return [(httpProtocolTypes.HTTP, bytes_(self.config.pac_file_url_path))]
+            return [(httpProtocolTypes.HTTP, bytes_(
+                self.config.pac_file_url_path))]
         return []
 
     def handle_request(self, request: HttpParser) -> None:
@@ -1411,9 +1425,8 @@ class ProtocolHandler(threading.Thread):
         conn = self.optionally_wrap_socket(self.fromfd(fileno))
         if conn is None:
             raise TcpConnectionUninitializedException()
-        self.client: TcpClientConnection = TcpClientConnection(
-            conn=conn,
-            addr=addr)
+        self.client: TcpClientConnection = \
+            TcpClientConnection(conn=conn, addr=addr)
 
         self.plugins: Dict[str, ProtocolHandlerPlugin] = {}
         if b'ProtocolHandlerPlugin' in self.config.plugins:
@@ -1426,7 +1439,8 @@ class ProtocolHandler(threading.Thread):
             fileno, family=socket.AF_INET if self.config.hostname.version == 4 else socket.AF_INET6,
             type=socket.SOCK_STREAM)
 
-    def optionally_wrap_socket(self, conn: socket.socket) -> Optional[Union[ssl.SSLSocket, socket.socket]]:
+    def optionally_wrap_socket(
+            self, conn: socket.socket) -> Optional[Union[ssl.SSLSocket, socket.socket]]:
         """Attempts to wrap accepted client connection using provided certificates.
 
         Shutdown and closes client connection upon error.
@@ -1642,14 +1656,18 @@ def load_plugins(plugins: bytes) -> Dict[bytes, List[type]]:
         if module_name == 'proxy':
             klass = getattr(sys.modules[__name__], text_(klass_name))
         else:
-            klass = getattr(importlib.import_module(text_(module_name)), text_(klass_name))
+            klass = getattr(
+                importlib.import_module(
+                    text_(module_name)),
+                text_(klass_name))
         base_klass = inspect.getmro(klass)[1]
         p[bytes_(base_klass.__name__)].append(klass)
         logger.info(
             'Loaded %s %s.%s',
             'plugin' if klass.__name__ != 'HttpWebServerRouteHandler' else 'route',
             text_(module_name),
-            # HttpWebServerRouteHandler route decorator adds a special staticmethod to return decorated function name
+            # HttpWebServerRouteHandler route decorator adds a special
+            # staticmethod to return decorated function name
             klass.__name__ if klass.__name__ != 'HttpWebServerRouteHandler' else klass.name())
     return p
 
@@ -1897,7 +1915,7 @@ def main(input_args: List[str]) -> None:
             config=config)
         if args.pid_file:
             with open(args.pid_file, 'wb') as pid_file:
-                pid_file.write(bytes_(str(os.getpid())))
+                pid_file.write(bytes_(os.getpid()))
         server.run()
     except KeyboardInterrupt:  # pragma: no cover
         pass
diff --git a/requirements-release.txt b/requirements-release.txt
index f3c2cd3..e506590 100644
--- a/requirements-release.txt
+++ b/requirements-release.txt
@@ -1,1 +1,3 @@
 twine==2.0.0
+wheel==0.33.6
+setuptools==40.6.2


Test patch:
diff --git a/tests.py b/tests.py
index d00e075..1eba932 100644
--- a/tests.py
+++ b/tests.py
@@ -106,7 +106,8 @@ class TestTcpConnection(unittest.TestCase):
         self.assertTrue(self.conn.closed)
 
     @mock.patch('socket.socket')
-    def testTcpServerEstablishesIPv6Connection(self, mock_socket: mock.Mock) -> None:
+    def testTcpServerEstablishesIPv6Connection(
+            self, mock_socket: mock.Mock) -> None:
         conn = proxy.TcpServerConnection(
             str(proxy.DEFAULT_IPV6_HOSTNAME), proxy.DEFAULT_PORT)
         conn.connect()
@@ -115,7 +116,8 @@ class TestTcpConnection(unittest.TestCase):
             (str(proxy.DEFAULT_IPV6_HOSTNAME), proxy.DEFAULT_PORT, 0, 0))
 
     @mock.patch('socket.socket')
-    def testTcpServerEstablishesIPv4Connection(self, mock_socket: mock.Mock) -> None:
+    def testTcpServerEstablishesIPv4Connection(
+            self, mock_socket: mock.Mock) -> None:
         conn = proxy.TcpServerConnection(
             str(proxy.DEFAULT_IPV4_HOSTNAME), proxy.DEFAULT_PORT)
         conn.connect()
@@ -214,15 +216,19 @@ class TestTcpServer(unittest.TestCase):
     # Example, simply sending http traffic to HTTPS server.
     @mock.patch('select.select')
     @mock.patch('socket.socket')
-    def testAcceptSSLErrorsSilentlyIgnored(self, mock_socket: mock.Mock, mock_select: mock.Mock) -> None:
+    def testAcceptSSLErrorsSilentlyIgnored(
+            self, mock_socket: mock.Mock, mock_select: mock.Mock) -> None:
         mock_socket.accept.side_effect = ssl.SSLError()
         mock_select.return_value = ([mock_socket], [], [])
-        server = TcpServerUnderTest(hostname=proxy.DEFAULT_IPV6_HOSTNAME, port=1234)
+        server = TcpServerUnderTest(
+            hostname=proxy.DEFAULT_IPV6_HOSTNAME, port=1234)
         server.socket = mock_socket
         with mock.patch('proxy.logger') as mock_logger:
             server.run_once()
             mock_logger.exception.assert_called()
-            self.assertTrue(mock_logger.exception.call_args[0][0], 'SSLError encountered')
+            self.assertTrue(
+                mock_logger.exception.call_args[0][0],
+                'SSLError encountered')
 
 
 class TestChunkParser(unittest.TestCase):
@@ -304,7 +310,8 @@ class TestHttpParser(unittest.TestCase):
 
     def test_build_request(self) -> None:
         self.assertEqual(
-            proxy.HttpParser.build_request(b'GET', b'http://localhost:12345', b'HTTP/1.1'),
+            proxy.HttpParser.build_request(
+                b'GET', b'http://localhost:12345', b'HTTP/1.1'),
             proxy.CRLF.join([
                 b'GET http://localhost:12345 HTTP/1.1',
                 proxy.CRLF
@@ -329,7 +336,8 @@ class TestHttpParser(unittest.TestCase):
 
     def test_build_response(self) -> None:
         self.assertEqual(
-            proxy.HttpParser.build_response(200, reason=b'OK', protocol_version=b'HTTP/1.1'),
+            proxy.HttpParser.build_response(
+                200, reason=b'OK', protocol_version=b'HTTP/1.1'),
             proxy.CRLF.join([
                 b'HTTP/1.1 200 OK',
                 proxy.CRLF
@@ -352,7 +360,7 @@ class TestHttpParser(unittest.TestCase):
             proxy.CRLF.join([
                 b'HTTP/1.1 200 OK',
                 b'key: value',
-                b'Content-Length: ' + proxy.bytes_(str(len(body))),
+                b'Content-Length: ' + proxy.bytes_(len(body)),
                 proxy.CRLF
             ]) + body)
 
@@ -742,11 +750,13 @@ class TestHttpProtocolHandler(unittest.TestCase):
         self.fileno = 10
         self._addr = ('127.0.0.1', 54382)
         self._conn = mock_fromfd.return_value
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=self.config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=self.config)
 
     @mock.patch('select.select')
     @mock.patch('proxy.TcpServerConnection')
-    def test_http_get(self, mock_server_connection: mock.Mock, mock_select: mock.Mock) -> None:
+    def test_http_get(self, mock_server_connection: mock.Mock,
+                      mock_select: mock.Mock) -> None:
         server = mock_server_connection.return_value
         server.connect.return_value = True
         mock_select.side_effect = [
@@ -779,9 +789,11 @@ class TestHttpProtocolHandler(unittest.TestCase):
         self.proxy.run_once()
         server.flush.assert_called_once()
 
-    def assert_tunnel_response(self, mock_server_connection: mock.Mock, server: mock.Mock) -> None:
+    def assert_tunnel_response(
+            self, mock_server_connection: mock.Mock, server: mock.Mock) -> None:
         self.proxy.run_once()
-        self.assertTrue(self.proxy.plugins['HttpProxyPlugin'].server is not None)  # type: ignore
+        self.assertTrue(
+            self.proxy.plugins['HttpProxyPlugin'].server is not None)  # type: ignore
         self.assertEqual(
             self.proxy.client.buffer,
             proxy.HttpProxyPlugin.PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT)
@@ -798,7 +810,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     @mock.patch('select.select')
     @mock.patch('proxy.TcpServerConnection')
-    def test_http_tunnel(self, mock_server_connection: mock.Mock, mock_select: mock.Mock) -> None:
+    def test_http_tunnel(self, mock_server_connection: mock.Mock,
+                         mock_select: mock.Mock) -> None:
         server = mock_server_connection.return_value
         server.connect.return_value = True
         server.has_buffer.side_effect = [False, False, False, True]
@@ -841,7 +854,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     @mock.patch('socket.fromfd')
     @mock.patch('select.select')
-    def test_proxy_authentication_failed(self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
+    def test_proxy_authentication_failed(
+            self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
         self._conn = mock_fromfd.return_value
         mock_select.return_value = ([self._conn], [], [])
         config = proxy.ProtocolConfig(
@@ -849,7 +863,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
                       base64.b64encode(b'user:pass'))
         config.plugins = proxy.load_plugins(
             b'proxy.HttpProxyPlugin,proxy.HttpWebServerPlugin')
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=config)
         self._conn.recv.return_value = proxy.CRLF.join([
             b'GET http://abhinavsingh.com HTTP/1.1',
             b'Host: abhinavsingh.com',
@@ -878,7 +893,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
         config.plugins = proxy.load_plugins(
             b'proxy.HttpProxyPlugin,proxy.HttpWebServerPlugin')
 
-        self.proxy = proxy.ProtocolHandler(self.fileno, addr=self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, addr=self._addr, config=config)
         assert self.http_server_port is not None
 
         self._conn.recv.return_value = b'GET http://localhost:%d HTTP/1.1' % self.http_server_port
@@ -924,7 +940,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
         config.plugins = proxy.load_plugins(
             b'proxy.HttpProxyPlugin,proxy.HttpWebServerPlugin')
 
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=config)
 
         assert self.http_server_port is not None
         self._conn.recv.return_value = proxy.CRLF.join([
@@ -944,7 +961,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     @mock.patch('socket.fromfd')
     @mock.patch('select.select')
-    def test_pac_file_served_from_disk(self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
+    def test_pac_file_served_from_disk(
+            self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
         pac_file = 'proxy.pac'
         self._conn = mock_fromfd.return_value
         mock_select.return_value = [self._conn], [], []
@@ -963,7 +981,8 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     @mock.patch('socket.fromfd')
     @mock.patch('select.select')
-    def test_pac_file_served_from_buffer(self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
+    def test_pac_file_served_from_buffer(
+            self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
         self._conn = mock_fromfd.return_value
         pac_file_content = b'function FindProxyForURL(url, host) { return "PROXY localhost:8899; DIRECT"; }'
         mock_select.return_value = [self._conn], [], []
@@ -981,13 +1000,15 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     @mock.patch('socket.fromfd')
     @mock.patch('select.select')
-    def test_default_web_server_returns_404(self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
+    def test_default_web_server_returns_404(
+            self, mock_select: mock.Mock, mock_fromfd: mock.Mock) -> None:
         self._conn = mock_fromfd.return_value
         mock_select.return_value = [self._conn], [], []
         config = proxy.ProtocolConfig()
         config.plugins = proxy.load_plugins(
             b'proxy.HttpProxyPlugin,proxy.HttpWebServerPlugin')
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=config)
         self._conn.recv.return_value = proxy.CRLF.join([
             b'GET /hello HTTP/1.1',
             proxy.CRLF,
@@ -1002,12 +1023,14 @@ class TestHttpProtocolHandler(unittest.TestCase):
             proxy.HttpWebServerPlugin.DEFAULT_404_RESPONSE)
 
     @mock.patch('socket.fromfd')
-    def test_on_client_connection_called_on_teardown(self, mock_fromfd: mock.Mock) -> None:
+    def test_on_client_connection_called_on_teardown(
+            self, mock_fromfd: mock.Mock) -> None:
         config = proxy.ProtocolConfig()
         plugin = mock.MagicMock()
         config.plugins = {b'ProtocolHandlerPlugin': [plugin]}
         self._conn = mock_fromfd.return_value
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=config)
         plugin.assert_called()
         with mock.patch.object(self.proxy, 'run_once') as mock_run_once:
             mock_run_once.return_value = True
@@ -1020,13 +1043,15 @@ class TestHttpProtocolHandler(unittest.TestCase):
         config = proxy.ProtocolConfig(pac_file=pac_file)
         config.plugins = proxy.load_plugins(
             b'proxy.HttpProxyPlugin,proxy.HttpWebServerPlugin,proxy.HttpWebServerPacFilePlugin')
-        self.proxy = proxy.ProtocolHandler(self.fileno, self._addr, config=config)
+        self.proxy = proxy.ProtocolHandler(
+            self.fileno, self._addr, config=config)
         self._conn.recv.return_value = proxy.CRLF.join([
             b'GET / HTTP/1.1',
             proxy.CRLF,
         ])
 
-    def assert_data_queued(self, mock_server_connection: mock.Mock, server: mock.Mock) -> None:
+    def assert_data_queued(
+            self, mock_server_connection: mock.Mock, server: mock.Mock) -> None:
         self.proxy.run_once()
         self.assertEqual(
             self.proxy.request.state,
@@ -1046,7 +1071,9 @@ class TestHttpProtocolHandler(unittest.TestCase):
 
     def assert_data_queued_to_server(self, server: mock.Mock) -> None:
         assert self.http_server_port is not None
-        self.assertEqual(self._conn.send.call_args[0][0], proxy.HttpProxyPlugin.PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT)
+        self.assertEqual(
+            self._conn.send.call_args[0][0],
+            proxy.HttpProxyPlugin.PROXY_TUNNEL_ESTABLISHED_RESPONSE_PKT)
 
         self._conn.recv.return_value = proxy.CRLF.join([
             b'GET / HTTP/1.1',
@@ -1069,7 +1096,10 @@ class TestWorker(unittest.TestCase):
     @mock.patch('proxy.ProtocolHandler')
     def setUp(self, mock_protocol_handler: mock.Mock) -> None:
         self.pipe = multiprocessing.Pipe()
-        self.worker = proxy.Worker(self.pipe[1], mock_protocol_handler, config=proxy.ProtocolConfig())
+        self.worker = proxy.Worker(
+            self.pipe[1],
+            mock_protocol_handler,
+            config=proxy.ProtocolConfig())
         self.mock_protocol_handler = mock_protocol_handler
 
     @mock.patch('proxy.ProtocolHandler')
@@ -1079,7 +1109,8 @@ class TestWorker(unittest.TestCase):
         self.assertFalse(mock_http_proxy.called)
 
     @mock.patch('proxy.recv_handle')
-    def test_spawns_http_proxy_threads(self, mock_recv_handle: mock.Mock) -> None:
+    def test_spawns_http_proxy_threads(
+            self, mock_recv_handle: mock.Mock) -> None:
         fileno = 10
         mock_recv_handle.return_value = fileno
         self.pipe[0].send((proxy.workerOperations.HTTP_PROTOCOL, None))
@@ -1167,7 +1198,7 @@ class TestMain(unittest.TestCase):
         mock_multicore_dispatcher.return_value.run.assert_called()
         mock_open.assert_called_with(pid_file, 'wb')
         mock_open.return_value.__enter__.return_value.write.assert_called_with(
-            proxy.bytes_(str(os.getpid())))
+            proxy.bytes_(os.getpid()))
         mock_exists.assert_called_with(pid_file)
         mock_remove.assert_called_with(pid_file)
 
@@ -1272,12 +1303,18 @@ class TestMain(unittest.TestCase):
     def test_text(self) -> None:
         self.assertEqual(proxy.text_(b'hello'), 'hello')
 
+    def test_text_int(self) -> None:
+        self.assertEqual(proxy.text_(1), '1')
+
     def test_text_nochange(self) -> None:
         self.assertEqual(proxy.text_('hello'), 'hello')
 
     def test_bytes(self) -> None:
         self.assertEqual(proxy.bytes_('hello'), b'hello')
 
+    def test_bytes_int(self) -> None:
+        self.assertEqual(proxy.bytes_(1), b'1')
+
     def test_bytes_nochange(self) -> None:
         self.assertEqual(proxy.bytes_(b'hello'), b'hello')
 
@@ -1286,7 +1323,8 @@ class TestMain(unittest.TestCase):
         'Open file limit tests disabled for Windows')
     @mock.patch('resource.getrlimit', return_value=(128, 1024))  # type: ignore
     @mock.patch('resource.setrlimit', return_value=None)
-    def test_set_open_file_limit(self, mock_set_rlimit, mock_get_rlimit) -> None:
+    def test_set_open_file_limit(
+            self, mock_set_rlimit, mock_get_rlimit) -> None:
         proxy.set_open_file_limit(256)
         mock_get_rlimit.assert_called_with(resource.RLIMIT_NOFILE)
         mock_set_rlimit.assert_called_with(resource.RLIMIT_NOFILE, (256, 1024))