internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: urllib3/urllib3

Issue:
PyOpenSSL support doesn't work with TLSv1.1 and TLSv1.2
`docker-py` tries to use latest protocol version in the ssl module, so use ssl.PROTOCOL_TLSv1_2. Unfortunately urllib3.contrib.pyopenssl only has SSLv2_3 and TLSv1 so it breaks:

https://github.com/shazow/urllib3/blob/master/urllib3/contrib/pyopenssl.py#L68



Discussion:
Seems like a good idea to me. =)

To be clear this should be an extremely simple fix: conditionally attempt to use the TLSv1_1 and TLSv1_2 names, and if they exist then add them to the versions map.  This is a great 'first contribution' task.

+1, @itamarst would you like to do a PR for this?

Might have a few free minutes at work tomorrow, maybe.


Resolving patch:
diff --git a/urllib3/contrib/pyopenssl.py b/urllib3/contrib/pyopenssl.py
--- a/urllib3/contrib/pyopenssl.py
+++ b/urllib3/contrib/pyopenssl.py
@@ -71,6 +71,12 @@
     ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
 }
 
+if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):
+    _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
+
+if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):
+    _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
+
 try:
     _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})
 except AttributeError:


Test patch:
Repository: urllib3/urllib3

Issue:
Catch socket.error in error_catcher
Originally spotted in kennethreitz/requests#1236. It turns out that during `stream` a `socket.error` can get raised that isn't wrapped by httplib. We should catch and wrap those ourselves.



Discussion:

Resolving patch:
diff --git a/urllib3/response.py b/urllib3/response.py
--- a/urllib3/response.py
+++ b/urllib3/response.py
@@ -3,6 +3,7 @@
 import zlib
 import io
 from socket import timeout as SocketTimeout
+from socket import error as SocketError
 
 from ._collections import HTTPHeaderDict
 from .exceptions import (
@@ -238,9 +239,10 @@ def _error_catcher(self):
 
                 raise ReadTimeoutError(self._pool, None, 'Read timed out.')
 
-            except HTTPException as e:
+            except (HTTPException, SocketError) as e:
                 # This includes IncompleteRead.
                 raise ProtocolError('Connection broken: %r' % e, e)
+
         except Exception:
             # The response may not be closed but we're not going to use it anymore
             # so close it now to ensure that the connection is released back to the pool.


Test patch:
Repository: urllib3/urllib3

Issue:
ca_cert_dir keyword argument may be passed to HTTPConnectionPool by accident.
Seems like as part of #701 I missed the `SSL_KEYWORDS` block in `poolmanager.py`. This means that `ca_cert_dir` may accidentally be passed to the `HTTPConnectionPool`.  This leads to the following error when attempting to use `ca_cert_dir` with a `PoolManager` and then making a plaintext HTTP connection:

```
>>> import urllib3
>>> p = urllib3.PoolManager(ca_cert_dir='/usr/local/etc/openssl')
>>> p.urlopen('GET', 'http://http2bin.org/get')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "urllib3/poolmanager.py", line 162, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "urllib3/connectionpool.py", line 548, in urlopen
    conn = self._get_conn(timeout=pool_timeout)
  File "urllib3/connectionpool.py", line 250, in _get_conn
    return conn or self._new_conn()
  File "urllib3/connectionpool.py", line 211, in _new_conn
    strict=self.strict, **self.conn_kw)
  File "urllib3/connection.py", line 121, in __init__
    _HTTPConnection.__init__(self, *args, **kw)
TypeError: __init__() got an unexpected keyword argument 'ca_cert_dir'
```



Discussion:
This should also make sure to update the new tests in #751 to include the ca_cert_dir field.

Mmm that is pretty nasty.


Resolving patch:
diff --git a/urllib3/poolmanager.py b/urllib3/poolmanager.py
--- a/urllib3/poolmanager.py
+++ b/urllib3/poolmanager.py
@@ -26,7 +26,7 @@
 log = logging.getLogger(__name__)
 
 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',
-                'ssl_version')
+                'ssl_version', 'ca_cert_dir')
 
 
 class PoolManager(RequestMethods):


Test patch:
diff --git a/test/with_dummyserver/test_poolmanager.py b/test/with_dummyserver/test_poolmanager.py
--- a/test/with_dummyserver/test_poolmanager.py
+++ b/test/with_dummyserver/test_poolmanager.py
@@ -162,6 +162,12 @@ def test_http_with_ssl_keywords(self):
         r = http.request('GET', 'http://%s:%s/' % (self.host, self.port))
         self.assertEqual(r.status, 200)
 
+    def test_http_with_ca_cert_dir(self):
+        http = PoolManager(ca_certs='REQUIRED', ca_cert_dir='/nosuchdir')
+
+        r = http.request('GET', 'http://%s:%s/' % (self.host, self.port))
+        self.assertEqual(r.status, 200)
+
 
 class TestIPv6PoolManager(IPv6HTTPDummyServerTestCase):
     if not HAS_IPV6:
Repository: urllib3/urllib3

Issue:
Broken vendoring in socks contrib module
Awkwardly, the SOCKS contrib module doesn't work properly when vendored because it tries to do an absolute import. We should probably rewrite it to use relative imports.

My bad.



Discussion:

Resolving patch:
diff --git a/urllib3/contrib/socks.py b/urllib3/contrib/socks.py
--- a/urllib3/contrib/socks.py
+++ b/urllib3/contrib/socks.py
@@ -21,7 +21,7 @@
     import socks
 except ImportError:
     import warnings
-    from urllib3.exceptions import DependencyWarning
+    from ..exceptions import DependencyWarning
 
     warnings.warn((
         'SOCKS support in urllib3 requires the installation of optional '
@@ -34,15 +34,15 @@
 
 from socket import error as SocketError, timeout as SocketTimeout
 
-from urllib3.connection import (
+from ..connection import (
     HTTPConnection, HTTPSConnection
 )
-from urllib3.connectionpool import (
+from ..connectionpool import (
     HTTPConnectionPool, HTTPSConnectionPool
 )
-from urllib3.exceptions import ConnectTimeoutError, NewConnectionError
-from urllib3.poolmanager import PoolManager
-from urllib3.util.url import parse_url
+from ..exceptions import ConnectTimeoutError, NewConnectionError
+from ..poolmanager import PoolManager
+from ..util.url import parse_url
 
 try:
     import ssl


Test patch:
Repository: urllib3/urllib3

Issue:
Honor PYTHONWARNINGS for SNIMissingWarning
.local/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
.local/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning

I'm not here to discuss the validity of those warnings, but when I tried to get rid of them with the PYTHONWARNINGS environment variable, it only works for the InsecurePlatformWarning one. The other is always displayed whatever I put in PYTHONWARNINGS.

Please advise what PYTHONWARNINGS value to use to get rid of this one, this is a documented python feature: 
https://docs.python.org/2/library/warnings.html
https://docs.python.org/2/using/cmdline.html?highlight=pythonwarnings#envvar-PYTHONWARNINGS

Also seen the same problem here: in https://github.com/shazow/urllib3/issues/497

Thanks



Discussion:

Resolving patch:
diff --git a/urllib3/__init__.py b/urllib3/__init__.py
--- a/urllib3/__init__.py
+++ b/urllib3/__init__.py
@@ -74,15 +74,18 @@ def add_stderr_logger(level=logging.DEBUG):
 del NullHandler
 
 
+# All warning filters *must* be appended unless you're really certain that they
+# shouldn't be: otherwise, it's very hard for users to use most Python
+# mechanisms to silence them.
 # SecurityWarning's always go off by default.
 warnings.simplefilter('always', exceptions.SecurityWarning, append=True)
 # SubjectAltNameWarning's should go off once per host
-warnings.simplefilter('default', exceptions.SubjectAltNameWarning)
+warnings.simplefilter('default', exceptions.SubjectAltNameWarning, append=True)
 # InsecurePlatformWarning's don't vary between requests, so we keep it default.
 warnings.simplefilter('default', exceptions.InsecurePlatformWarning,
                       append=True)
 # SNIMissingWarnings should go off only once.
-warnings.simplefilter('default', exceptions.SNIMissingWarning)
+warnings.simplefilter('default', exceptions.SNIMissingWarning, append=True)
 
 
 def disable_warnings(category=exceptions.HTTPWarning):


Test patch:
Repository: urllib3/urllib3

Issue:
Cannot run tests on Ubuntu 14.04 LTS + Python 3
#### Repro Steps

```
# (Install Docker from: http://www.docker.com )

# If OS X, start with:
$ docker-machine start default; eval "$(docker-machine env default)"

# If OS X or Linux, continue with:
$ docker run -it ubuntu:trusty  # Ubuntu 14.04 LTS
$$ apt-get update
$$ apt-get install git -y
$$ apt-get install python3-pip -y
$$ pip3 install virtualenv
$$ git clone https://github.com/shazow/urllib3
$$ cd urllib3/
$$ virtualenv venv
$$ source venv/bin/activate
$$ make test
```
#### Output

```
python setup.py develop
Traceback (most recent call last):
  File "setup.py", line 23, in <module>
    long_description=open('README.rst').read() + '\n\n' + open('CHANGES.rst').read(),
  File "/urllib3/venv/lib/python3.4/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 4597: ordinal not in range(128)
make: *** [*.egg-info] Error 1
```
#### Notes

My best guess is that the `read()`s in setup.py should have an encoding specified. Probably UTF-8.



Discussion:
Likely fix that works on Python 2 and 3: `io.open('README.rst', encoding='utf8')`

Oh you support Python 2.6 too. Here's a more-compatible version: `codecs.open('README.rst', encoding='utf8')`

Hm strange, can't reproduce the error on Python 3.5. Does changing it to `u'\n\n'` help at all?

``` diff
- long_description=open('README.rst').read() + '\n\n' + open('CHANGES.rst').read(),
+ long_description=open('README.rst').read() + u'\n\n' + open('CHANGES.rst').read(),
```

This is _almost certainly_ a locale problem. We can resolve it in one of two ways:
- we could purge all non-acsii characters from the changelog and readme and keep them purged
- we can just use the change to `codecs` to ensure that they're always opened and decoded as UTF-8.

I feel like the second one is the best approach.

I can reproduce with `export LC_ALL=C` on Ubuntu 14.04. If it's all right, I can have a PR ready in a bit.

I'm happy to review.


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@
 
 import os
 import re
-
+import codecs
 
 base_path = os.path.dirname(__file__)
 
@@ -14,13 +14,14 @@
                      re.S).match(fp.read()).group(1)
 fp.close()
 
-
+readme = codecs.open('README.rst', encoding='utf-8').read()
+changes = codecs.open('README.rst', encoding='utf-8').read()
 version = VERSION
 
 setup(name='urllib3',
       version=version,
       description="HTTP library with thread-safe connection pooling, file post, and more.",
-      long_description=open('README.rst').read() + '\n\n' + open('CHANGES.rst').read(),
+      long_description=u'\n\n'.join([readme, changes]),
       classifiers=[
           'Environment :: Web Environment',
           'Intended Audience :: Developers',


Test patch:
Repository: urllib3/urllib3

Issue:
PyOpenSSL: Fails to import after installation with the provided instructions
The [Security documentation page](https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl) indicates that to use PyOpenSSL that you must first install:
- pip3 install pyopenssl ndg-httpsclient pyasn1

And then in a Python interpreter run:
- import urllib3.contrib.pyopenssl
- urllib3.contrib.pyopenssl.inject_into_urllib3()

However on Python 3.4.4 (the latest 3.4.x) on OS X 10.11 (the latest OS X) I get the following traceback when executing `import urllib3.contrib.pyopenssl`:

```
Traceback (most recent call last):
  File "/Users/davidf/Projects/webcrystal/venv/lib/python3.4/site-packages/urllib3/contrib/pyopenssl.py", line 60, in <module>
    from socket import _fileobject
ImportError: cannot import name '_fileobject'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/davidf/Projects/webcrystal/venv/lib/python3.4/site-packages/urllib3/contrib/pyopenssl.py", line 63, in <module>
    from urllib3.packages.backports.makefile import backport_makefile
ImportError: No module named 'urllib3.packages.backports'
```

Perhaps there is some missing step in the documentation?



Discussion:
Nope, that looks like a real bug to me!

In particular, this looks like we incorrectly packaged the release. We added a new module that appears to not be being collected for installation.

We'll be able to get a new release out for this specific problem quite quickly, I suspect. @shazow if I push up a fix, are you interested in running out a really quick .1 release with the fix?


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -40,7 +40,8 @@
       license='MIT',
       packages=['urllib3',
                 'urllib3.packages', 'urllib3.packages.ssl_match_hostname',
-                'urllib3.contrib', 'urllib3.util',
+                'urllib3.packages.backports', 'urllib3.contrib',
+                'urllib3.util',
                 ],
       requires=[],
       tests_require=[


Test patch:
Repository: urllib3/urllib3

Issue:
Remove 3DES from cipher suite.
Well, [3DES is broken now](https://sweet32.info/). This attack is difficult to mount against requests/urllib3, but not impossible, and so we should aim to remove 3DES support in the near future. We don't need to rush out a release for it though: the next release is fine.



Discussion:
For those who want a summary of why we're not at particular risk:

The attack requires that a large number of _authenticated_ requests be sent on a single HTTPS connection (where "large number" amounts to upwards of 32GB worth). This is possible to trigger in a browser using Javascript, but is extremely difficult to trigger in requests/urllib3. Statistically I suspect the only times requests/urllib3 transfer that much data on one TLS connection are when they are transferring large files.

However, it's definitely _possible_, so we should remove that attack surface from urllib3 as soon as reasonably possible.

As the scholar @hawkowl once said (ten minutes ago):

![](https://frinkiac.com/gif/S04E01/1157356/1164663.gif?b64lines=QnVybiwgM0RFUywgYnVybiE=)


Resolving patch:
diff --git a/urllib3/util/ssl_.py b/urllib3/util/ssl_.py
--- a/urllib3/util/ssl_.py
+++ b/urllib3/util/ssl_.py
@@ -65,7 +65,6 @@ def _const_compare_digest_backport(a, b):
 # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
 #   security,
 # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
-# - use 3DES as fallback which is secure but slow,
 # - disable NULL authentication, MD5 MACs and DSS for security reasons.
 DEFAULT_CIPHERS = ':'.join([
     'ECDH+AESGCM',
@@ -76,14 +75,8 @@ def _const_compare_digest_backport(a, b):
     'DH+AES256',
     'ECDH+AES128',
     'DH+AES',
-    'ECDH+HIGH',
-    'DH+HIGH',
-    'ECDH+3DES',
-    'DH+3DES',
     'RSA+AESGCM',
     'RSA+AES',
-    'RSA+HIGH',
-    'RSA+3DES',
     '!aNULL',
     '!eNULL',
     '!MD5',


Test patch:
Repository: urllib3/urllib3

Issue:
Chunked uploads do not deduplicate the Host header field.
When using `urlopen` with a headers dictionary that includes the `Host` header, the `Host` header from the user will be preferred to the automatic one added by httplib. This is not true when calling `urlopen` with `chunked=True`, because `request_chunked` does not have the same deduplication logic as `request` does.

We basically need to duplicate [this logic](https://github.com/python/cpython/blob/master/Lib/http/client.py#L1236-L1241).

Should be a pretty easy patch if anyone wants a quick contribution win. A test to prove that this doesn't work, followed by the patch to make it work. 
## 



Discussion:

Resolving patch:
diff --git a/urllib3/connection.py b/urllib3/connection.py
--- a/urllib3/connection.py
+++ b/urllib3/connection.py
@@ -170,7 +170,13 @@ def request_chunked(self, method, url, body=None, headers=None):
         """
         headers = HTTPHeaderDict(headers if headers is not None else {})
         skip_accept_encoding = 'accept-encoding' in headers
-        self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding)
+        skip_host = 'host' in headers
+        self.putrequest(
+            method,
+            url,
+            skip_accept_encoding=skip_accept_encoding,
+            skip_host=skip_host
+        )
         for header, value in headers.items():
             self.putheader(header, value)
         if 'transfer-encoding' not in headers:


Test patch:
diff --git a/test/with_dummyserver/test_chunked_transfer.py b/test/with_dummyserver/test_chunked_transfer.py
--- a/test/with_dummyserver/test_chunked_transfer.py
+++ b/test/with_dummyserver/test_chunked_transfer.py
@@ -74,3 +74,29 @@ def test_empty_string_body(self):
 
     def test_empty_iterable_body(self):
         self._test_body([])
+
+    def test_removes_duplicate_host_header(self):
+        self.start_chunked_handler()
+        chunks = ['foo', 'bar', '', 'bazzzzzzzzzzzzzzzzzzzzzz']
+        pool = HTTPConnectionPool(self.host, self.port, retries=False)
+        pool.urlopen(
+            'GET', '/', chunks, headers={'Host': 'test.org'}, chunked=True
+        )
+
+        header_block = self.buffer.split(b'\r\n\r\n', 1)[0].lower()
+        header_lines = header_block.split(b'\r\n')[1:]
+
+        host_headers = [x for x in header_lines if x.startswith(b'host')]
+        self.assertEqual(len(host_headers), 1)
+
+    def test_provides_default_host_header(self):
+        self.start_chunked_handler()
+        chunks = ['foo', 'bar', '', 'bazzzzzzzzzzzzzzzzzzzzzz']
+        pool = HTTPConnectionPool(self.host, self.port, retries=False)
+        pool.urlopen('GET', '/', chunks, chunked=True)
+
+        header_block = self.buffer.split(b'\r\n\r\n', 1)[0].lower()
+        header_lines = header_block.split(b'\r\n')[1:]
+
+        host_headers = [x for x in header_lines if x.startswith(b'host')]
+        self.assertEqual(len(host_headers), 1)
Repository: urllib3/urllib3

Issue:
Add unit test for RECENT_DATE
I've got a feeling this value could be easily forgotten to be updated over time. Could we perhaps add a unit test that will fail if it gets to be too far away from the current date.  It seems like it was last modified in mid 2014 but wasn't updated since then, should this value be updated now?

Link to the blame: https://github.com/shazow/urllib3/blame/master/urllib3/connection.py#L59
## 



Discussion:
We should probably consider updating this sometime soon, yeah. Might be worth having a unit test.

Perhaps having a maximum distance from the current date of 2 years?  Also, should I update it to 2015 perhaps? I can submit a PR for this if that's what's wanted.

Why don't we just determine it programmatically during the test? :trollface: 


Resolving patch:
diff --git a/urllib3/connection.py b/urllib3/connection.py
--- a/urllib3/connection.py
+++ b/urllib3/connection.py
@@ -56,7 +56,10 @@ class ConnectionError(Exception):
     'https': 443,
 }
 
-RECENT_DATE = datetime.date(2014, 1, 1)
+# When updating RECENT_DATE, move it to
+# within two years of the current date, and no
+# earlier than 6 months ago.
+RECENT_DATE = datetime.date(2016, 1, 1)
 
 
 class DummyConnection(object):


Test patch:
diff --git a/test/test_connection.py b/test/test_connection.py
--- a/test/test_connection.py
+++ b/test/test_connection.py
@@ -1,4 +1,9 @@
-import unittest
+import datetime
+import sys
+if sys.version_info >= (2, 7):
+    import unittest
+else:
+    import unittest2 as unittest
 
 import mock
 
@@ -6,6 +11,7 @@
     CertificateError,
     VerifiedHTTPSConnection,
     _match_hostname,
+    RECENT_DATE
 )
 
 
@@ -43,6 +49,14 @@ def test_match_hostname_mismatch(self):
             )
             self.assertEqual(e._peer_cert, cert)
 
+    def test_recent_date(self):
+        # This test is to make sure that the RECENT_DATE value
+        # doesn't get too far behind what the current date is.
+        # When this test fails update urllib3.connection.RECENT_DATE
+        # according to the rules defined in that file.
+        two_years = datetime.timedelta(days=365 * 2)
+        self.assertGreater(RECENT_DATE, (datetime.datetime.today() - two_years).date())
+
 
 if __name__ == '__main__':
     unittest.main()
Repository: urllib3/urllib3

Issue:
test_selectors.py tests fail with python 2.6 64bit and 27 64bit on windows 
I have noticed that there are a number of tests like the `test_selectors.py::BaseSelectorTestCase::test_register` fail when run against python 2.6 64 bit and python 2.7 64bit. (see appveyor builds, 
https://ci.appveyor.com/project/itziakos/urllib3/build/1.0.7/job/m0xhyhhl05xdcmxi and https://ci.appveyor.com/project/itziakos/urllib3/build/1.0.7/job/i23k8bf88787c199)

The error is due to the fact that `socket.fileno()` returns a `long` on python 2.6 and 2.7  (64bits) and the 
[urllib3.util.selectors._fileobj_to_fd](https://github.com/shazow/urllib3/blob/master/urllib3/util/selectors.py#L41) does not specifically handle that case and the function will finally raise a [ValueError](https://github.com/shazow/urllib3/blob/master/urllib3/util/selectors.py#L50)

The interesting part is that the error was not picked up by the appveyor tests because tox will use the 32 bit python when running the tests.

*output from example build https://ci.appveyor.com/project/itziakos/urllib3/build/1.0.9/job/j84qscx038440brd#L248*
```
py26 runtests: PYTHONHASHSEED='187'
py26 runtests: commands[0] | pip --version
pip 9.0.1 from c:\projects\urllib3\.tox\py26\lib\site-packages (python 2.6)
py26 runtests: commands[1] | python -c import struct; print(struct.calcsize('P') * 8)
32
py26 runtests: commands[2] | pip install .[socks,secure]
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Processing c:\projects\urllib3
  Requirement already satisfied (use --upgrade to upgrade): urllib3===dev from file:///C:/projects/urllib3 in c:\projects\urllib3\.tox\py26\lib\site-packages
```

If it is ok, I can make a PR to fix the issue and attempt to persuade tox to use the 64bit python on appveyor.



Discussion:
That would be fantastic, thanks!

Resolving patch:
diff --git a/urllib3/util/selectors.py b/urllib3/util/selectors.py
--- a/urllib3/util/selectors.py
+++ b/urllib3/util/selectors.py
@@ -12,12 +12,14 @@
 import sys
 import time
 from collections import namedtuple, Mapping
+from ..packages.six import integer_types
 
 try:
     monotonic = time.monotonic
 except (AttributeError, ImportError):  # Python 3.3<
     monotonic = time.time
 
+
 EVENT_READ = (1 << 0)
 EVENT_WRITE = (1 << 1)
 
@@ -41,7 +43,7 @@ def __str__(self):
 def _fileobj_to_fd(fileobj):
     """ Return a file descriptor from a file object. If
     given an integer will simply return that integer back. """
-    if isinstance(fileobj, int):
+    if isinstance(fileobj, integer_types):
         fd = fileobj
     else:
         try:


Test patch: