summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorRatan Kulshreshtha <RatanShreshtha@users.noreply.github.com>2019-05-28 20:49:36 +0530
committerSeth Michael Larson <sethmichaellarson@gmail.com>2019-05-28 10:19:36 -0500
commit52c827532d8b434e6bd344fad7ee69b9d247792b (patch)
tree0d7f70b4d84f11804e0c0967cd14f6a3ce88195f /test
parentf7a4bed04085975918b3469bf94e195df9faf29a (diff)
downloadurllib3-52c827532d8b434e6bd344fad7ee69b9d247792b.tar.gz
Update assertions to pytest style (#1614)
Diffstat (limited to 'test')
-rw-r--r--test/appengine/test_gae_manager.py62
-rw-r--r--test/appengine/test_urlfetch.py8
-rw-r--r--test/contrib/test_pyopenssl.py12
-rw-r--r--test/contrib/test_pyopenssl_dependencies.py6
-rw-r--r--test/contrib/test_socks.py141
-rw-r--r--test/test_no_ssl.py3
-rw-r--r--test/with_dummyserver/test_chunked_transfer.py20
-rw-r--r--test/with_dummyserver/test_connectionpool.py344
-rw-r--r--test/with_dummyserver/test_https.py148
-rw-r--r--test/with_dummyserver/test_no_ssl.py4
-rw-r--r--test/with_dummyserver/test_poolmanager.py76
-rw-r--r--test/with_dummyserver/test_proxy_poolmanager.py166
-rw-r--r--test/with_dummyserver/test_socketlevel.py194
13 files changed, 568 insertions, 616 deletions
diff --git a/test/appengine/test_gae_manager.py b/test/appengine/test_gae_manager.py
index 2581813f..572c387b 100644
--- a/test/appengine/test_gae_manager.py
+++ b/test/appengine/test_gae_manager.py
@@ -45,48 +45,28 @@ class TestGAEConnectionManager(test_connectionpool.TestConnectionPool):
def test_exceptions(self):
# DeadlineExceededError -> TimeoutError
- self.assertRaises(
- urllib3.exceptions.TimeoutError,
- self.pool.request,
- "GET",
- "/sleep?seconds=0.005",
- timeout=0.001,
- )
+ with pytest.raises(urllib3.exceptions.TimeoutError):
+ self.pool.request("GET", "/sleep?seconds=0.005", timeout=0.001)
# InvalidURLError -> ProtocolError
- self.assertRaises(
- urllib3.exceptions.ProtocolError,
- self.manager.request,
- "GET",
- "ftp://invalid/url",
- )
+ with pytest.raises(urllib3.exceptions.ProtocolError):
+ self.manager.request("GET", "ftp://invalid/url")
# DownloadError -> ProtocolError
- self.assertRaises(
- urllib3.exceptions.ProtocolError,
- self.manager.request,
- "GET",
- "http://0.0.0.0",
- )
+ with pytest.raises(urllib3.exceptions.ProtocolError):
+ self.manager.request("GET", "http://0.0.0.0")
# ResponseTooLargeError -> AppEnginePlatformError
- self.assertRaises(
- appengine.AppEnginePlatformError,
- self.pool.request,
- "GET",
- "/nbytes?length=33554433",
- ) # One byte over 32 megabtyes.
+ with pytest.raises(appengine.AppEnginePlatformError):
+ self.pool.request(
+ "GET", "/nbytes?length=33554433"
+ ) # One byte over 32 megabtyes.
# URLFetch reports the request too large error as a InvalidURLError,
# which maps to a AppEnginePlatformError.
body = b"1" * 10485761 # One byte over 10 megabytes.
- self.assertRaises(
- appengine.AppEnginePlatformError,
- self.manager.request,
- "POST",
- "/",
- body=body,
- )
+ with pytest.raises(appengine.AppEnginePlatformError):
+ self.manager.request("POST", "/", body=body)
# Re-used tests below this line.
# Subsumed tests
@@ -133,7 +113,8 @@ class TestGAEConnectionManagerWithSSL(dummyserver.testcase.HTTPSDummyServerTestC
# SSLCertificateError -> SSLError
# SSLError is raised with dummyserver because URLFetch doesn't allow
# self-signed certs.
- self.assertRaises(urllib3.exceptions.SSLError, self.pool.request, "GET", "/")
+ with pytest.raises(urllib3.exceptions.SSLError):
+ self.pool.request("GET", "/")
@pytest.mark.usefixtures("testbed")
@@ -152,7 +133,7 @@ class TestGAERetry(test_connectionpool.TestRetry):
headers={"test-name": "test_default_whitelist"},
retries=retry,
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_retry_return_in_response(self):
headers = {"test-name": "test_retry_return_in_response"}
@@ -160,15 +141,12 @@ class TestGAERetry(test_connectionpool.TestRetry):
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 200)
- self.assertEqual(resp.retries.total, 1)
+ assert resp.status == 200
+ assert resp.retries.total == 1
# URLFetch use absolute urls.
- self.assertEqual(
- resp.retries.history,
- (
- urllib3.util.retry.RequestHistory(
- "GET", self.pool._absolute_url("/successful_retry"), None, 418, None
- ),
+ assert resp.retries.history == (
+ urllib3.util.retry.RequestHistory(
+ "GET", self.pool._absolute_url("/successful_retry"), None, 418, None
),
)
diff --git a/test/appengine/test_urlfetch.py b/test/appengine/test_urlfetch.py
index 37561b76..056de924 100644
--- a/test/appengine/test_urlfetch.py
+++ b/test/appengine/test_urlfetch.py
@@ -40,8 +40,8 @@ class TestHTTP(TestWithoutSSL):
pool = urllib3.HTTPConnectionPool("www.google.com", "80")
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
- self.assertEqual(fetch_mock.call_count, 1)
+ assert r.status == 200, r.data
+ assert fetch_mock.call_count == 1
@pytest.mark.usefixtures("sandbox")
@@ -64,5 +64,5 @@ class TestHTTPS(unittest.TestCase):
pool = urllib3.HTTPSConnectionPool("www.google.com", "443")
pool.ConnectionCls = urllib3.connection.UnverifiedHTTPSConnection
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
- self.assertEqual(fetch_mock.call_count, 1)
+ assert r.status == 200, r.data
+ assert fetch_mock.call_count == 1
diff --git a/test/contrib/test_pyopenssl.py b/test/contrib/test_pyopenssl.py
index b0c44ae9..56656dae 100644
--- a/test/contrib/test_pyopenssl.py
+++ b/test/contrib/test_pyopenssl.py
@@ -61,7 +61,7 @@ class TestPyOpenSSLHelpers(unittest.TestCase):
name = u"उदाहरण.परीक"
expected_result = "xn--p1b6ci4b4b3a.xn--11b5bs8d"
- self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+ assert _dnsname_to_stdlib(name) == expected_result
def test_dnsname_to_stdlib_leading_period(self):
"""
@@ -70,7 +70,7 @@ class TestPyOpenSSLHelpers(unittest.TestCase):
name = u".उदाहरण.परीक"
expected_result = ".xn--p1b6ci4b4b3a.xn--11b5bs8d"
- self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+ assert _dnsname_to_stdlib(name) == expected_result
def test_dnsname_to_stdlib_leading_splat(self):
"""
@@ -80,7 +80,7 @@ class TestPyOpenSSLHelpers(unittest.TestCase):
name = u"*.उदाहरण.परीक"
expected_result = "*.xn--p1b6ci4b4b3a.xn--11b5bs8d"
- self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+ assert _dnsname_to_stdlib(name) == expected_result
@mock.patch("urllib3.contrib.pyopenssl.log.warning")
def test_get_subj_alt_name(self, mock_warning):
@@ -92,7 +92,7 @@ class TestPyOpenSSLHelpers(unittest.TestCase):
with open(path, "r") as fp:
cert = load_certificate(FILETYPE_PEM, fp.read())
- self.assertEqual(get_subj_alt_name(cert), [])
+ assert get_subj_alt_name(cert) == []
- self.assertEqual(mock_warning.call_count, 1)
- self.assertIsInstance(mock_warning.call_args[0][1], x509.DuplicateExtension)
+ assert mock_warning.call_count == 1
+ assert isinstance(mock_warning.call_args[0][1], x509.DuplicateExtension)
diff --git a/test/contrib/test_pyopenssl_dependencies.py b/test/contrib/test_pyopenssl_dependencies.py
index 1024a9cf..c5e93e06 100644
--- a/test/contrib/test_pyopenssl_dependencies.py
+++ b/test/contrib/test_pyopenssl_dependencies.py
@@ -40,7 +40,8 @@ class TestPyOpenSSLInjection(unittest.TestCase):
try:
with patch("cryptography.x509.extensions.Extensions") as mock:
del mock.get_extension_for_class
- self.assertRaises(ImportError, inject_into_urllib3)
+ with pytest.raises(ImportError):
+ inject_into_urllib3()
finally:
# `inject_into_urllib3` is not supposed to succeed.
# If it does, this test should fail, but we need to
@@ -55,7 +56,8 @@ class TestPyOpenSSLInjection(unittest.TestCase):
return_val = Mock()
del return_val._x509
with patch("OpenSSL.crypto.X509", return_value=return_val):
- self.assertRaises(ImportError, inject_into_urllib3)
+ with pytest.raises(ImportError):
+ inject_into_urllib3()
finally:
# `inject_into_urllib3` is not supposed to succeed.
# If it does, this test should fail, but we need to
diff --git a/test/contrib/test_socks.py b/test/contrib/test_socks.py
index 20c88b42..8a253a8f 100644
--- a/test/contrib/test_socks.py
+++ b/test/contrib/test_socks.py
@@ -211,8 +211,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks5_negotiation(sock, negotiate=False)
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -234,9 +234,9 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
def test_local_dns(self):
def request_handler(listener):
@@ -245,8 +245,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks5_negotiation(sock, negotiate=False)
addr, port = next(handler)
- self.assertIn(addr, ["127.0.0.1", "::1"])
- self.assertEqual(port, 80)
+ assert addr in ["127.0.0.1", "::1"]
+ assert port == 80
handler.send(True)
while True:
@@ -268,9 +268,9 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "http://localhost")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
def test_correct_header_line(self):
def request_handler(listener):
@@ -279,8 +279,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks5_negotiation(sock, negotiate=False)
addr, port = next(handler)
- self.assertEqual(addr, b"example.com")
- self.assertEqual(port, 80)
+ assert addr == b"example.com"
+ assert port == 80
handler.send(True)
buf = b""
@@ -289,8 +289,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
if buf.endswith(b"\r\n\r\n"):
break
- self.assertTrue(buf.startswith(b"GET / HTTP/1.1"))
- self.assertIn(b"Host: example.com", buf)
+ assert buf.startswith(b"GET / HTTP/1.1")
+ assert b"Host: example.com" in buf
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
@@ -305,7 +305,7 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
pm = socks.SOCKSProxyManager(proxy_url)
self.addCleanup(pm.clear)
response = pm.request("GET", "http://example.com")
- self.assertEqual(response.status, 200)
+ assert response.status == 200
def test_connection_timeouts(self):
event = threading.Event()
@@ -318,14 +318,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
pm = socks.SOCKSProxyManager(proxy_url)
self.addCleanup(pm.clear)
- self.assertRaises(
- ConnectTimeoutError,
- pm.request,
- "GET",
- "http://example.com",
- timeout=0.001,
- retries=False,
- )
+ with pytest.raises(ConnectTimeoutError):
+ pm.request("GET", "http://example.com", timeout=0.001, retries=False)
event.set()
def test_connection_failure(self):
@@ -341,9 +335,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
event.wait()
- self.assertRaises(
- NewConnectionError, pm.request, "GET", "http://example.com", retries=False
- )
+ with pytest.raises(NewConnectionError):
+ pm.request("GET", "http://example.com", retries=False)
def test_proxy_rejection(self):
evt = threading.Event()
@@ -363,9 +356,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
pm = socks.SOCKSProxyManager(proxy_url)
self.addCleanup(pm.clear)
- self.assertRaises(
- NewConnectionError, pm.request, "GET", "http://example.com", retries=False
- )
+ with pytest.raises(NewConnectionError):
+ pm.request("GET", "http://example.com", retries=False)
evt.set()
def test_socks_with_password(self):
@@ -377,8 +369,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
)
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -401,9 +393,9 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
def test_socks_with_auth_in_url(self):
"""
@@ -419,8 +411,8 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
)
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -443,9 +435,9 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
def test_socks_with_invalid_password(self):
def request_handler(listener):
@@ -464,7 +456,7 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
try:
pm.request("GET", "http://example.com", retries=False)
except NewConnectionError as e:
- self.assertIn("SOCKS5 authentication failed", str(e))
+ assert "SOCKS5 authentication failed" in str(e)
else:
self.fail("Did not raise")
@@ -473,14 +465,14 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
def request_handler(listener):
sock = listener.accept()[0]
- self.assertEqual(sock.getpeername()[0], "127.0.0.1")
- self.assertEqual(sock.getpeername()[1], expected_port)
+ assert sock.getpeername()[0] == "127.0.0.1"
+ assert sock.getpeername()[1] == expected_port
handler = handle_socks5_negotiation(sock, negotiate=False)
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -503,7 +495,7 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
)
self.addCleanup(pm.clear)
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
+ assert response.status == 200
class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
@@ -521,8 +513,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks4_negotiation(sock)
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -544,9 +536,9 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.headers["Server"], "SocksTestServer")
- self.assertEqual(response.data, b"")
+ assert response.status == 200
+ assert response.headers["Server"] == "SocksTestServer"
+ assert response.data == b""
def test_local_dns(self):
def request_handler(listener):
@@ -555,8 +547,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks4_negotiation(sock)
addr, port = next(handler)
- self.assertEqual(addr, "127.0.0.1")
- self.assertEqual(port, 80)
+ assert addr == "127.0.0.1"
+ assert port == 80
handler.send(True)
while True:
@@ -578,9 +570,9 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "http://localhost")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.headers["Server"], "SocksTestServer")
- self.assertEqual(response.data, b"")
+ assert response.status == 200
+ assert response.headers["Server"] == "SocksTestServer"
+ assert response.data == b""
def test_correct_header_line(self):
def request_handler(listener):
@@ -589,8 +581,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks4_negotiation(sock)
addr, port = next(handler)
- self.assertEqual(addr, b"example.com")
- self.assertEqual(port, 80)
+ assert addr == b"example.com"
+ assert port == 80
handler.send(True)
buf = b""
@@ -599,8 +591,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
if buf.endswith(b"\r\n\r\n"):
break
- self.assertTrue(buf.startswith(b"GET / HTTP/1.1"))
- self.assertIn(b"Host: example.com", buf)
+ assert buf.startswith(b"GET / HTTP/1.1")
+ assert b"Host: example.com" in buf
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
@@ -615,7 +607,7 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
pm = socks.SOCKSProxyManager(proxy_url)
self.addCleanup(pm.clear)
response = pm.request("GET", "http://example.com")
- self.assertEqual(response.status, 200)
+ assert response.status == 200
def test_proxy_rejection(self):
evt = threading.Event()
@@ -635,9 +627,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
pm = socks.SOCKSProxyManager(proxy_url)
self.addCleanup(pm.clear)
- self.assertRaises(
- NewConnectionError, pm.request, "GET", "http://example.com", retries=False
- )
+ with pytest.raises(NewConnectionError):
+ pm.request("GET", "http://example.com", retries=False)
evt.set()
def test_socks4_with_username(self):
@@ -647,8 +638,8 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
handler = handle_socks4_negotiation(sock, username=b"user")
addr, port = next(handler)
- self.assertEqual(addr, "16.17.18.19")
- self.assertEqual(port, 80)
+ assert addr == "16.17.18.19"
+ assert port == 80
handler.send(True)
while True:
@@ -670,9 +661,9 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "http://16.17.18.19")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
def test_socks_with_invalid_username(self):
def request_handler(listener):
@@ -689,7 +680,7 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
try:
pm.request("GET", "http://example.com", retries=False)
except NewConnectionError as e:
- self.assertIn("different user-ids", str(e))
+ assert "different user-ids" in str(e)
else:
self.fail("Did not raise")
@@ -707,8 +698,8 @@ class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase):
handler = handle_socks5_negotiation(sock, negotiate=False)
addr, port = next(handler)
- self.assertEqual(addr, b"localhost")
- self.assertEqual(port, 443)
+ assert addr == b"localhost"
+ assert port == 443
handler.send(True)
# Wrap in TLS
@@ -722,7 +713,7 @@ class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase):
if buf.endswith(b"\r\n\r\n"):
break
- self.assertTrue(buf.startswith(b"GET / HTTP/1.1\r\n"))
+ assert buf.startswith(b"GET / HTTP/1.1\r\n")
tls.sendall(
b"HTTP/1.1 200 OK\r\n"
@@ -739,6 +730,6 @@ class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase):
self.addCleanup(pm.clear)
response = pm.request("GET", "https://localhost")
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"")
- self.assertEqual(response.headers["Server"], "SocksTestServer")
+ assert response.status == 200
+ assert response.data == b""
+ assert response.headers["Server"] == "SocksTestServer"
diff --git a/test/test_no_ssl.py b/test/test_no_ssl.py
index 76c407cf..7d1a129f 100644
--- a/test/test_no_ssl.py
+++ b/test/test_no_ssl.py
@@ -7,6 +7,7 @@ Test what happens if Python was built without SSL
import sys
import unittest
+import pytest
class ImportBlocker(object):
@@ -78,7 +79,7 @@ class TestWithoutSSL(unittest.TestCase):
class TestImportWithoutSSL(TestWithoutSSL):
def test_cannot_import_ssl(self):
- with self.assertRaises(ImportError):
+ with pytest.raises(ImportError):
import ssl # noqa: F401
def test_import_urllib3(self):
diff --git a/test/with_dummyserver/test_chunked_transfer.py b/test/with_dummyserver/test_chunked_transfer.py
index b176e63c..c5746ddd 100644
--- a/test/with_dummyserver/test_chunked_transfer.py
+++ b/test/with_dummyserver/test_chunked_transfer.py
@@ -31,14 +31,14 @@ class TestChunkedTransfer(SocketDummyServerTestCase):
pool.urlopen("GET", "/", chunks, headers=dict(DNT="1"), chunked=True)
self.addCleanup(pool.close)
- self.assertIn(b"Transfer-Encoding", self.buffer)
+ assert b"Transfer-Encoding" in self.buffer
body = self.buffer.split(b"\r\n\r\n", 1)[1]
lines = body.split(b"\r\n")
# Empty chunks should have been skipped, as this could not be distinguished
# from terminating the transmission
for i, chunk in enumerate([c for c in chunks if c]):
- self.assertEqual(lines[i * 2], hex(len(chunk))[2:].encode("utf-8"))
- self.assertEqual(lines[i * 2 + 1], chunk.encode("utf-8"))
+ assert lines[i * 2] == hex(len(chunk))[2:].encode("utf-8")
+ assert lines[i * 2 + 1] == chunk.encode("utf-8")
def _test_body(self, data):
self.start_chunked_handler()
@@ -48,17 +48,17 @@ class TestChunkedTransfer(SocketDummyServerTestCase):
pool.urlopen("GET", "/", data, chunked=True)
header, body = self.buffer.split(b"\r\n\r\n", 1)
- self.assertIn(b"Transfer-Encoding: chunked", header.split(b"\r\n"))
+ assert b"Transfer-Encoding: chunked" in header.split(b"\r\n")
if data:
bdata = data if isinstance(data, bytes) else data.encode("utf-8")
- self.assertIn(b"\r\n" + bdata + b"\r\n", body)
- self.assertTrue(body.endswith(b"\r\n0\r\n\r\n"))
+ assert b"\r\n" + bdata + b"\r\n" in body
+ assert body.endswith(b"\r\n0\r\n\r\n")
len_str = body.split(b"\r\n", 1)[0]
stated_len = int(len_str, 16)
- self.assertEqual(stated_len, len(bdata))
+ assert stated_len == len(bdata)
else:
- self.assertEqual(body, b"0\r\n\r\n")
+ assert body == b"0\r\n\r\n"
def test_bytestring_body(self):
self._test_body(b"thisshouldbeonechunk\r\nasdf")
@@ -91,7 +91,7 @@ class TestChunkedTransfer(SocketDummyServerTestCase):
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)
+ assert len(host_headers) == 1
def test_provides_default_host_header(self):
self.start_chunked_handler()
@@ -104,4 +104,4 @@ class TestChunkedTransfer(SocketDummyServerTestCase):
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)
+ assert len(host_headers) == 1
diff --git a/test/with_dummyserver/test_connectionpool.py b/test/with_dummyserver/test_connectionpool.py
index 99d40226..65580055 100644
--- a/test/with_dummyserver/test_connectionpool.py
+++ b/test/with_dummyserver/test_connectionpool.py
@@ -56,7 +56,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
)
self.addCleanup(pool.close)
wait_for_socket(ready_event)
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/")
block_event.set() # Release block
# Shouldn't raise this time
@@ -79,7 +80,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
self.fail("The request should fail with a timeout error.")
except ReadTimeoutError:
if conn.sock:
- self.assertRaises(socket.error, conn.sock.recv, 1024)
+ with pytest.raises(socket.error):
+ conn.sock.recv(1024)
finally:
pool._put_conn(conn)
@@ -97,13 +99,15 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
wait_for_socket(ready_event)
conn = pool._get_conn()
- self.assertRaises(ReadTimeoutError, pool._make_request, conn, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool._make_request(conn, "GET", "/")
pool._put_conn(conn)
block_event.set() # Release request
wait_for_socket(ready_event)
block_event.clear()
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/")
block_event.set() # Release request
# Request-specific timeouts should raise errors
@@ -115,44 +119,37 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
conn = pool._get_conn()
wait_for_socket(ready_event)
now = time.time()
- self.assertRaises(
- ReadTimeoutError, pool._make_request, conn, "GET", "/", timeout=timeout
- )
+ with pytest.raises(ReadTimeoutError):
+ pool._make_request(conn, "GET", "/", timeout=timeout)
delta = time.time() - now
block_event.set() # Release request
message = "timeout was pool-level LONG_TIMEOUT rather than request-level SHORT_TIMEOUT"
- self.assertLess(delta, LONG_TIMEOUT, message)
+ assert delta < LONG_TIMEOUT, message
pool._put_conn(conn)
wait_for_socket(ready_event)
now = time.time()
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/", timeout=timeout)
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/", timeout=timeout)
delta = time.time() - now
message = "timeout was pool-level LONG_TIMEOUT rather than request-level SHORT_TIMEOUT"
- self.assertLess(delta, LONG_TIMEOUT, message)
+ assert delta < LONG_TIMEOUT, message
block_event.set() # Release request
# Timeout int/float passed directly to request and _make_request should
# raise a request timeout
wait_for_socket(ready_event)
- self.assertRaises(
- ReadTimeoutError, pool.request, "GET", "/", timeout=SHORT_TIMEOUT
- )
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/", timeout=SHORT_TIMEOUT)
block_event.set() # Release request
wait_for_socket(ready_event)
conn = pool._new_conn()
# FIXME: This assert flakes sometimes. Not sure why.
- self.assertRaises(
- ReadTimeoutError,
- pool._make_request,
- conn,
- "GET",
- "/",
- timeout=SHORT_TIMEOUT,
- )
+ with pytest.raises(ReadTimeoutError):
+ pool._make_request(conn, "GET", "/", timeout=SHORT_TIMEOUT)
block_event.set() # Release request
def test_connect_timeout(self):
@@ -164,25 +161,25 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
pool = HTTPConnectionPool(host, port, timeout=timeout)
self.addCleanup(pool.close)
conn = pool._get_conn()
- self.assertRaises(ConnectTimeoutError, pool._make_request, conn, "GET", url)
+ with pytest.raises(ConnectTimeoutError):
+ pool._make_request(conn, "GET", url)
# Retries
retries = Retry(connect=0)
- self.assertRaises(MaxRetryError, pool.request, "GET", url, retries=retries)
+ with pytest.raises(MaxRetryError):
+ pool.request("GET", url, retries=retries)
# Request-specific connection timeouts
big_timeout = Timeout(read=LONG_TIMEOUT, connect=LONG_TIMEOUT)
pool = HTTPConnectionPool(host, port, timeout=big_timeout, retries=False)
self.addCleanup(pool.close)
conn = pool._get_conn()
- self.assertRaises(
- ConnectTimeoutError, pool._make_request, conn, "GET", url, timeout=timeout
- )
+ with pytest.raises(ConnectTimeoutError):
+ pool._make_request(conn, "GET", url, timeout=timeout)
pool._put_conn(conn)
- self.assertRaises(
- ConnectTimeoutError, pool.request, "GET", url, timeout=timeout
- )
+ with pytest.raises(ConnectTimeoutError):
+ pool.request("GET", url, timeout=timeout)
def test_total_applies_connect(self):
host, port = TARPIT_HOST, 80
@@ -192,14 +189,16 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
self.addCleanup(pool.close)
conn = pool._get_conn()
self.addCleanup(conn.close)
- self.assertRaises(ConnectTimeoutError, pool._make_request, conn, "GET", "/")
+ with pytest.raises(ConnectTimeoutError):
+ pool._make_request(conn, "GET", "/")
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT)
pool = HTTPConnectionPool(host, port, timeout=timeout)
self.addCleanup(pool.close)
conn = pool._get_conn()
self.addCleanup(conn.close)
- self.assertRaises(ConnectTimeoutError, pool._make_request, conn, "GET", "/")
+ with pytest.raises(ConnectTimeoutError):
+ pool._make_request(conn, "GET", "/")
def test_total_timeout(self):
block_event = Event()
@@ -210,7 +209,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
timeout = Timeout(connect=3, read=SHORT_TIMEOUT)
pool = HTTPConnectionPool(self.host, self.port, timeout=timeout, retries=False)
self.addCleanup(pool.close)
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/")
block_event.set()
wait_for_socket(ready_event)
@@ -220,7 +220,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT)
pool = HTTPConnectionPool(self.host, self.port, timeout=timeout, retries=False)
self.addCleanup(pool.close)
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/")
def test_create_connection_timeout(self):
self.start_basic_handler(block_send=Event(), num=0) # needed for self.port
@@ -231,7 +232,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
)
self.addCleanup(pool.close)
conn = pool._new_conn()
- self.assertRaises(ConnectTimeoutError, conn.connect)
+ with pytest.raises(ConnectTimeoutError):
+ conn.connect()
class TestConnectionPool(HTTPDummyServerTestCase):
@@ -241,23 +243,23 @@ class TestConnectionPool(HTTPDummyServerTestCase):
def test_get(self):
r = self.pool.request("GET", "/specific_method", fields={"method": "GET"})
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_post_url(self):
r = self.pool.request("POST", "/specific_method", fields={"method": "POST"})
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_urlopen_put(self):
r = self.pool.urlopen("PUT", "/specific_method?method=PUT")
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_wrong_specific_method(self):
# To make sure the dummy server is actually returning failed responses
r = self.pool.request("GET", "/specific_method", fields={"method": "POST"})
- self.assertEqual(r.status, 400, r.data)
+ assert r.status == 400, r.data
r = self.pool.request("POST", "/specific_method", fields={"method": "GET"})
- self.assertEqual(r.status, 400, r.data)
+ assert r.status == 400, r.data
def test_upload(self):
data = "I'm in ur multipart form-data, hazing a cheezburgr"
@@ -269,28 +271,27 @@ class TestConnectionPool(HTTPDummyServerTestCase):
}
r = self.pool.request("POST", "/upload", fields=fields)
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_one_name_multiple_values(self):
fields = [("foo", "a"), ("foo", "b")]
# urlencode
r = self.pool.request("GET", "/echo", fields=fields)
- self.assertEqual(r.data, b"foo=a&foo=b")
+ assert r.data == b"foo=a&foo=b"
# multipart
r = self.pool.request("POST", "/echo", fields=fields)
- self.assertEqual(r.data.count(b'name="foo"'), 2)
+ assert r.data.count(b'name="foo"') == 2
def test_request_method_body(self):
body = b"hi"
r = self.pool.request("POST", "/echo", body=body)
- self.assertEqual(r.data, body)
+ assert r.data == body
fields = [("hi", "hello")]
- self.assertRaises(
- TypeError, self.pool.request, "POST", "/echo", body=body, fields=fields
- )
+ with pytest.raises(TypeError):
+ self.pool.request("POST", "/echo", body=body, fields=fields)
def test_unicode_upload(self):
fieldname = u("myfile")
@@ -306,7 +307,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
}
r = self.pool.request("POST", "/upload", fields=fields)
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_nagle(self):
""" Test that connections have TCP_NODELAY turned on """
@@ -320,7 +321,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
tcp_nodelay_setting = conn.sock.getsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY
)
- self.assertTrue(tcp_nodelay_setting)
+ assert tcp_nodelay_setting
def test_socket_options(self):
"""Test that connections accept socket options."""
@@ -333,7 +334,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
)
s = pool._new_conn()._new_conn() # Get the socket
using_keepalive = s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
- self.assertTrue(using_keepalive)
+ assert using_keepalive
s.close()
def test_disable_default_socket_options(self):
@@ -343,7 +344,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
pool = HTTPConnectionPool(self.host, self.port, socket_options=None)
s = pool._new_conn()._new_conn()
using_nagle = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) == 0
- self.assertTrue(using_nagle)
+ assert using_nagle
s.close()
def test_defaults_are_applied(self):
@@ -361,8 +362,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
self.addCleanup(s.close)
nagle_disabled = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0
using_keepalive = s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
- self.assertTrue(nagle_disabled)
- self.assertTrue(using_keepalive)
+ assert nagle_disabled
+ assert using_keepalive
def test_connection_error_retries(self):
""" ECONNREFUSED error should raise a connection error, with retries """
@@ -372,7 +373,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
pool.request("GET", "/", retries=Retry(connect=3))
self.fail("Should have failed with a connection error.")
except MaxRetryError as e:
- self.assertEqual(type(e.reason), NewConnectionError)
+ assert type(e.reason) == NewConnectionError
def test_timeout_success(self):
timeout = Timeout(connect=3, read=5, total=None)
@@ -414,17 +415,17 @@ class TestConnectionPool(HTTPDummyServerTestCase):
conn._tunnel = mock.Mock(return_value=None)
pool._make_request(conn, "GET", "/")
- self.assertFalse(conn._tunnel.called)
+ assert not conn._tunnel.called
def test_redirect(self):
r = self.pool.request(
"GET", "/redirect", fields={"target": "/"}, redirect=False
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = self.pool.request("GET", "/redirect", fields={"target": "/"})
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_bad_connect(self):
pool = HTTPConnectionPool("badhost.invalid", self.port)
@@ -432,7 +433,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
pool.request("GET", "/", retries=5)
self.fail("should raise timeout exception here")
except MaxRetryError as e:
- self.assertEqual(type(e.reason), NewConnectionError)
+ assert type(e.reason) == NewConnectionError
def test_keepalive(self):
pool = HTTPConnectionPool(self.host, self.port, block=True, maxsize=1)
@@ -441,9 +442,9 @@ class TestConnectionPool(HTTPDummyServerTestCase):
r = pool.request("GET", "/keepalive?close=0")
r = pool.request("GET", "/keepalive?close=0")
- self.assertEqual(r.status, 200)
- self.assertEqual(pool.num_connections, 1)
- self.assertEqual(pool.num_requests, 2)
+ assert r.status == 200
+ assert pool.num_connections == 1
+ assert pool.num_requests == 2
def test_keepalive_close(self):
pool = HTTPConnectionPool(
@@ -455,7 +456,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
)
- self.assertEqual(pool.num_connections, 1)
+ assert pool.num_connections == 1
# The dummyserver will have responded with Connection:close,
# and httplib will properly cleanup the socket.
@@ -464,7 +465,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
# because _get_conn() is where the check & reset occurs
# pylint: disable-msg=W0212
conn = pool.pool.get()
- self.assertIsNone(conn.sock)
+ assert conn.sock is None
pool._put_conn(conn)
# Now with keep-alive
@@ -475,7 +476,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
# The dummyserver responded with Connection:keep-alive, the connection
# persists.
conn = pool.pool.get()
- self.assertIsNotNone(conn.sock)
+ assert conn.sock is not None
pool._put_conn(conn)
# Another request asking the server to close the connection. This one
@@ -484,10 +485,10 @@ class TestConnectionPool(HTTPDummyServerTestCase):
"GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"}
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
conn = pool.pool.get()
- self.assertIsNone(conn.sock)
+ assert conn.sock is None
pool._put_conn(conn)
# Next request
@@ -496,7 +497,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
def test_post_with_urlencode(self):
data = {"banana": "hammock", "lol": "cat"}
r = self.pool.request("POST", "/echo", fields=data, encode_multipart=False)
- self.assertEqual(r.data.decode("utf-8"), urlencode(data))
+ assert r.data.decode("utf-8") == urlencode(data)
def test_post_with_multipart(self):
data = {"banana": "hammock", "lol": "cat"}
@@ -519,7 +520,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
if line.startswith(b"--"):
continue
- self.assertEqual(body[i], expected_body[i])
+ assert body[i] == expected_body[i]
def test_post_with_multipart__iter__(self):
data = {"hello": "world"}
@@ -545,32 +546,28 @@ class TestConnectionPool(HTTPDummyServerTestCase):
r = self.pool.request(
"GET", "/encodingrequest", headers={"accept-encoding": "gzip"}
)
- self.assertEqual(r.headers.get("content-encoding"), "gzip")
- self.assertEqual(r.data, b"hello, world!")
+ assert r.headers.get("content-encoding") == "gzip"
+ assert r.data == b"hello, world!"
def test_check_deflate(self):
r = self.pool.request(
"GET", "/encodingrequest", headers={"accept-encoding": "deflate"}
)
- self.assertEqual(r.headers.get("content-encoding"), "deflate")
- self.assertEqual(r.data, b"hello, world!")
+ assert r.headers.get("content-encoding") == "deflate"
+ assert r.data == b"hello, world!"
def test_bad_decode(self):
- self.assertRaises(
- DecodeError,
- self.pool.request,
- "GET",
- "/encodingrequest",
- headers={"accept-encoding": "garbage-deflate"},
- )
+ with pytest.raises(DecodeError):
+ self.pool.request(
+ "GET",
+ "/encodingrequest",
+ headers={"accept-encoding": "garbage-deflate"},
+ )
- self.assertRaises(
- DecodeError,
- self.pool.request,
- "GET",
- "/encodingrequest",
- headers={"accept-encoding": "garbage-gzip"},
- )
+ with pytest.raises(DecodeError):
+ self.pool.request(
+ "GET", "/encodingrequest", headers={"accept-encoding": "garbage-gzip"}
+ )
def test_connection_count(self):
pool = HTTPConnectionPool(self.host, self.port, maxsize=1)
@@ -580,8 +577,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
pool.request("GET", "/")
pool.request("GET", "/")
- self.assertEqual(pool.num_connections, 1)
- self.assertEqual(pool.num_requests, 3)
+ assert pool.num_connections == 1
+ assert pool.num_requests == 3
def test_connection_count_bigpool(self):
http_pool = HTTPConnectionPool(self.host, self.port, maxsize=16)
@@ -591,8 +588,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
http_pool.request("GET", "/")
http_pool.request("GET", "/")
- self.assertEqual(http_pool.num_connections, 1)
- self.assertEqual(http_pool.num_requests, 3)
+ assert http_pool.num_connections == 1
+ assert http_pool.num_requests == 3
def test_partial_response(self):
pool = HTTPConnectionPool(self.host, self.port, maxsize=1)
@@ -603,8 +600,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
r = pool.request("GET", "/echo", fields=req_data, preload_content=False)
- self.assertEqual(r.read(5), resp_data[:5])
- self.assertEqual(r.read(), resp_data[5:])
+ assert r.read(5) == resp_data[:5]
+ assert r.read() == resp_data[5:]
def test_lazy_load_twice(self):
# This test is sad and confusing. Need to figure out what's
@@ -633,7 +630,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
preload_content=False,
)
- self.assertEqual(r1.read(first_chunk), resp_data[:first_chunk])
+ assert r1.read(first_chunk) == resp_data[:first_chunk]
try:
r2 = pool.request(
@@ -648,17 +645,17 @@ class TestConnectionPool(HTTPDummyServerTestCase):
# This branch should generally bail here, but maybe someday it will
# work? Perhaps by some sort of magic. Consider it a TODO.
- self.assertEqual(r2.read(first_chunk), resp2_data[:first_chunk])
+ assert r2.read(first_chunk) == resp2_data[:first_chunk]
- self.assertEqual(r1.read(), resp_data[first_chunk:])
- self.assertEqual(r2.read(), resp2_data[first_chunk:])
- self.assertEqual(pool.num_requests, 2)
+ assert r1.read() == resp_data[first_chunk:]
+ assert r2.read() == resp2_data[first_chunk:]
+ assert pool.num_requests == 2
except EmptyPoolError:
- self.assertEqual(r1.read(), resp_data[first_chunk:])
- self.assertEqual(pool.num_requests, 1)
+ assert r1.read() == resp_data[first_chunk:]
+ assert pool.num_requests == 1
- self.assertEqual(pool.num_connections, 1)
+ assert pool.num_connections == 1
def test_for_double_release(self):
MAXSIZE = 5
@@ -666,45 +663,46 @@ class TestConnectionPool(HTTPDummyServerTestCase):
# Check default state
pool = HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE)
self.addCleanup(pool.close)
- self.assertEqual(pool.num_connections, 0)
- self.assertEqual(pool.pool.qsize(), MAXSIZE)
+ assert pool.num_connections == 0
+ assert pool.pool.qsize() == MAXSIZE
# Make an empty slot for testing
pool.pool.get()
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 1)
+ assert pool.pool.qsize() == MAXSIZE - 1
# Check state after simple request
pool.urlopen("GET", "/")
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 1)
+ assert pool.pool.qsize() == MAXSIZE - 1
# Check state without release
pool.urlopen("GET", "/", preload_content=False)
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 2)
+ assert pool.pool.qsize() == MAXSIZE - 2
pool.urlopen("GET", "/")
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 2)
+ assert pool.pool.qsize() == MAXSIZE - 2
# Check state after read
pool.urlopen("GET", "/").data
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 2)
+ assert pool.pool.qsize() == MAXSIZE - 2
pool.urlopen("GET", "/")
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 2)
+ assert pool.pool.qsize() == MAXSIZE - 2
def test_release_conn_parameter(self):
MAXSIZE = 5
pool = HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE)
- self.assertEqual(pool.pool.qsize(), MAXSIZE)
+ assert pool.pool.qsize() == MAXSIZE
# Make request without releasing connection
pool.request("GET", "/", release_conn=False, preload_content=False)
- self.assertEqual(pool.pool.qsize(), MAXSIZE - 1)
+ assert pool.pool.qsize() == MAXSIZE - 1
def test_dns_error(self):
pool = HTTPConnectionPool(
"thishostdoesnotexist.invalid", self.port, timeout=0.001
)
- self.assertRaises(MaxRetryError, pool.request, "GET", "/test", retries=2)
+ with pytest.raises(MaxRetryError):
+ pool.request("GET", "/test", retries=2)
def test_source_address(self):
for addr, is_ipv6 in VALID_SOURCE_ADDRESSES:
@@ -716,7 +714,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
)
self.addCleanup(pool.close)
r = pool.request("GET", "/source_address")
- self.assertEqual(r.data, b(addr[0]))
+ assert r.data == b(addr[0])
def test_source_address_error(self):
for addr in INVALID_SOURCE_ADDRESSES:
@@ -724,12 +722,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
self.host, self.port, source_address=addr, retries=False
)
# FIXME: This assert flakes sometimes. Not sure why.
- self.assertRaises(
- NewConnectionError,
- pool.request,
- "GET",
- "/source_address?{0}".format(addr),
- )
+ with pytest.raises(NewConnectionError):
+ pool.request("GET", "/source_address?{0}".format(addr))
def test_stream_keepalive(self):
x = 2
@@ -743,10 +737,10 @@ class TestConnectionPool(HTTPDummyServerTestCase):
retries=False,
)
for chunk in response.stream():
- self.assertEqual(chunk, b"123")
+ assert chunk == b"123"
- self.assertEqual(self.pool.num_connections, 1)
- self.assertEqual(self.pool.num_requests, x)
+ assert self.pool.num_connections == 1
+ assert self.pool.num_requests == x
def test_read_chunked_short_circuit(self):
response = self.pool.request("GET", "/chunked", preload_content=False)
@@ -765,7 +759,7 @@ class TestConnectionPool(HTTPDummyServerTestCase):
"GET", "/chunked_gzip", preload_content=False, decode_content=True
)
- self.assertEqual(b"123" * 4, response.read())
+ assert b"123" * 4 == response.read()
def test_cleanup_on_connection_error(self):
"""
@@ -776,20 +770,19 @@ class TestConnectionPool(HTTPDummyServerTestCase):
with HTTPConnectionPool(
self.host, self.port, maxsize=poolsize, block=True
) as http:
- self.assertEqual(http.pool.qsize(), poolsize)
+ assert http.pool.qsize() == poolsize
# force a connection error by supplying a non-existent
# url. We won't get a response for this and so the
# conn won't be implicitly returned to the pool.
- self.assertRaises(
- MaxRetryError,
- http.request,
- "GET",
- "/redirect",
- fields={"target": "/"},
- release_conn=False,
- retries=0,
- )
+ with pytest.raises(MaxRetryError):
+ http.request(
+ "GET",
+ "/redirect",
+ fields={"target": "/"},
+ release_conn=False,
+ retries=0,
+ )
r = http.request(
"GET",
@@ -801,13 +794,13 @@ class TestConnectionPool(HTTPDummyServerTestCase):
r.release_conn()
# the pool should still contain poolsize elements
- self.assertEqual(http.pool.qsize(), http.pool.maxsize)
+ assert http.pool.qsize() == http.pool.maxsize
def test_mixed_case_hostname(self):
pool = HTTPConnectionPool("LoCaLhOsT", self.port)
self.addCleanup(pool.close)
response = pool.request("GET", "http://LoCaLhOsT:%d/" % self.port)
- self.assertEqual(response.status, 200)
+ assert response.status == 200
class TestRetry(HTTPDummyServerTestCase):
@@ -825,19 +818,18 @@ class TestRetry(HTTPDummyServerTestCase):
def test_disabled_retry(self):
""" Disabled retries should disable redirect handling. """
r = self.pool.request("GET", "/redirect", fields={"target": "/"}, retries=False)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = self.pool.request(
"GET", "/redirect", fields={"target": "/"}, retries=Retry(redirect=False)
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
pool = HTTPConnectionPool(
"thishostdoesnotexist.invalid", self.port, timeout=0.001
)
- self.assertRaises(
- NewConnectionError, pool.request, "GET", "/test", retries=False
- )
+ with pytest.raises(NewConnectionError):
+ pool.request("GET", "/test", retries=False)
def test_read_retries(self):
""" Should retry for status codes in the whitelist """
@@ -848,7 +840,7 @@ class TestRetry(HTTPDummyServerTestCase):
headers={"test-name": "test_read_retries"},
retries=retry,
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_read_total_retries(self):
""" HTTP response w/ status code in the whitelist should be retried """
@@ -857,7 +849,7 @@ class TestRetry(HTTPDummyServerTestCase):
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_retries_wrong_whitelist(self):
"""HTTP response w/ status code not in whitelist shouldn't be retried"""
@@ -868,7 +860,7 @@ class TestRetry(HTTPDummyServerTestCase):
headers={"test-name": "test_wrong_whitelist"},
retries=retry,
)
- self.assertEqual(resp.status, 418)
+ assert resp.status == 418
def test_default_method_whitelist_retried(self):
""" urllib3 should retry methods in the default method whitelist """
@@ -879,7 +871,7 @@ class TestRetry(HTTPDummyServerTestCase):
headers={"test-name": "test_default_whitelist"},
retries=retry,
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_retries_wrong_method_list(self):
"""Method not in our whitelist should not be retried, even if code matches"""
@@ -888,12 +880,12 @@ class TestRetry(HTTPDummyServerTestCase):
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 418)
+ assert resp.status == 418
def test_read_retries_unsuccessful(self):
headers = {"test-name": "test_read_retries_unsuccessful"}
resp = self.pool.request("GET", "/successful_retry", headers=headers, retries=1)
- self.assertEqual(resp.status, 418)
+ assert resp.status == 418
def test_retry_reuse_safe(self):
""" It should be possible to reuse a Retry object across requests """
@@ -902,11 +894,11 @@ class TestRetry(HTTPDummyServerTestCase):
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_retry_return_in_response(self):
headers = {"test-name": "test_retry_return_in_response"}
@@ -914,19 +906,17 @@ class TestRetry(HTTPDummyServerTestCase):
resp = self.pool.request(
"GET", "/successful_retry", headers=headers, retries=retry
)
- self.assertEqual(resp.status, 200)
- self.assertEqual(resp.retries.total, 1)
- self.assertEqual(
- resp.retries.history,
- (RequestHistory("GET", "/successful_retry", None, 418, None),),
+ assert resp.status == 200
+ assert resp.retries.total == 1
+ assert resp.retries.history == (
+ RequestHistory("GET", "/successful_retry", None, 418, None),
)
def test_retry_redirect_history(self):
resp = self.pool.request("GET", "/redirect", fields={"target": "/"})
- self.assertEqual(resp.status, 200)
- self.assertEqual(
- resp.retries.history,
- (RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"),),
+ assert resp.status == 200
+ assert resp.retries.history == (
+ RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"),
)
def test_multi_redirect_history(self):
@@ -936,8 +926,8 @@ class TestRetry(HTTPDummyServerTestCase):
fields={"redirect_codes": "303,302,200"},
redirect=False,
)
- self.assertEqual(r.status, 303)
- self.assertEqual(r.retries.history, tuple())
+ assert r.status == 303
+ assert r.retries.history == tuple()
r = self.pool.request(
"GET",
@@ -945,8 +935,8 @@ class TestRetry(HTTPDummyServerTestCase):
retries=10,
fields={"redirect_codes": "303,302,301,307,302,200"},
)
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Done redirecting")
+ assert r.status == 200
+ assert r.data == b"Done redirecting"
expected = [
(303, "/multi_redirect?redirect_codes=302,301,307,302,200"),
@@ -958,7 +948,7 @@ class TestRetry(HTTPDummyServerTestCase):
actual = [
(history.status, history.redirect_location) for history in r.retries.history
]
- self.assertEqual(actual, expected)
+ assert actual == expected
class TestRetryAfter(HTTPDummyServerTestCase):
@@ -980,7 +970,7 @@ class TestRetryAfter(HTTPDummyServerTestCase):
fields={"status": "429 Too Many Requests"},
retries=False,
)
- self.assertEqual(r.status, 429)
+ assert r.status == 429
r = self.pool.request(
"GET",
@@ -988,7 +978,7 @@ class TestRetryAfter(HTTPDummyServerTestCase):
fields={"status": "429 Too Many Requests"},
retries=True,
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# Request twice in a second to get a 503 response.
r = self.pool.request(
@@ -1003,7 +993,7 @@ class TestRetryAfter(HTTPDummyServerTestCase):
fields={"status": "503 Service Unavailable"},
retries=False,
)
- self.assertEqual(r.status, 503)
+ assert r.status == 503
r = self.pool.request(
"GET",
@@ -1011,39 +1001,39 @@ class TestRetryAfter(HTTPDummyServerTestCase):
fields={"status": "503 Service Unavailable"},
retries=True,
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# Ignore Retry-After header on status which is not defined in
# Retry.RETRY_AFTER_STATUS_CODES.
r = self.pool.request(
"GET", "/retry_after", fields={"status": "418 I'm a teapot"}, retries=True
)
- self.assertEqual(r.status, 418)
+ assert r.status == 418
def test_redirect_after(self):
r = self.pool.request("GET", "/redirect_after", retries=False)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
t = time.time()
r = self.pool.request("GET", "/redirect_after")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
delta = time.time() - t
- self.assertGreaterEqual(delta, 1)
+ assert delta >= 1
t = time.time()
timestamp = t + 2
r = self.pool.request("GET", "/redirect_after?date=" + str(timestamp))
- self.assertEqual(r.status, 200)
+ assert r.status == 200
delta = time.time() - t
- self.assertGreaterEqual(delta, 1)
+ assert delta >= 1
# Retry-After is past
t = time.time()
timestamp = t - 1
r = self.pool.request("GET", "/redirect_after?date=" + str(timestamp))
delta = time.time() - t
- self.assertEqual(r.status, 200)
- self.assertLess(delta, 1)
+ assert r.status == 200
+ assert delta < 1
class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase):
@@ -1071,7 +1061,7 @@ class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase):
assert_same_host=False,
redirect=False,
)
- self.assertEqual(resp.status, 200)
+ assert resp.status == 200
def test_redirect_put_file(self):
"""PUT with file object should work with a redirection response"""
@@ -1094,8 +1084,8 @@ class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase):
assert_same_host=False,
redirect=True,
)
- self.assertEqual(resp.status, 200)
- self.assertEqual(resp.data, data)
+ assert resp.status == 200
+ assert resp.data == data
def test_redirect_with_failed_tell(self):
"""Abort request if failed to get a position from tell()"""
@@ -1113,7 +1103,7 @@ class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase):
self.pool.urlopen("PUT", url, headers=headers, body=body)
self.fail("PUT successful despite failed rewind.")
except UnrewindableBodyError as e:
- self.assertIn("Unable to record file position for", str(e))
+ assert "Unable to record file position for" in str(e)
class TestRetryPoolSize(HTTPDummyServerTestCase):
diff --git a/test/with_dummyserver/test_https.py b/test/with_dummyserver/test_https.py
index 6bda30fb..2f9ead51 100644
--- a/test/with_dummyserver/test_https.py
+++ b/test/with_dummyserver/test_https.py
@@ -86,13 +86,13 @@ class TestHTTPS(HTTPSDummyServerTestCase):
def test_simple(self):
r = self._pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
@fails_on_travis_gce
def test_dotted_fqdn(self):
pool = HTTPSConnectionPool(self.host + ".", self.port, ca_certs=DEFAULT_CA)
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_client_intermediate(self):
client_cert, client_key = (
@@ -188,11 +188,11 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self.addCleanup(https_pool.close)
conn = https_pool._new_conn()
- self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
+ assert conn.__class__ == VerifiedHTTPSConnection
with mock.patch("warnings.warn") as warn:
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# Modern versions of Python, or systems using PyOpenSSL, don't
# emit warnings.
@@ -201,15 +201,15 @@ class TestHTTPS(HTTPSDummyServerTestCase):
or util.IS_PYOPENSSL
or util.IS_SECURETRANSPORT
):
- self.assertFalse(warn.called, warn.call_args_list)
+ assert not warn.called, warn.call_args_list
else:
- self.assertTrue(warn.called)
+ assert warn.called
if util.HAS_SNI:
call = warn.call_args_list[0]
else:
call = warn.call_args_list[1]
error = call[0][1]
- self.assertEqual(error, InsecurePlatformWarning)
+ assert error == InsecurePlatformWarning
def test_verified_with_context(self):
ctx = util.ssl_.create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED)
@@ -218,11 +218,11 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self.addCleanup(https_pool.close)
conn = https_pool._new_conn()
- self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
+ assert conn.__class__ == VerifiedHTTPSConnection
with mock.patch("warnings.warn") as warn:
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# Modern versions of Python, or systems using PyOpenSSL, don't
# emit warnings.
@@ -231,15 +231,15 @@ class TestHTTPS(HTTPSDummyServerTestCase):
or util.IS_PYOPENSSL
or util.IS_SECURETRANSPORT
):
- self.assertFalse(warn.called, warn.call_args_list)
+ assert not warn.called, warn.call_args_list
else:
- self.assertTrue(warn.called)
+ assert warn.called
if util.HAS_SNI:
call = warn.call_args_list[0]
else:
call = warn.call_args_list[1]
error = call[0][1]
- self.assertEqual(error, InsecurePlatformWarning)
+ assert error == InsecurePlatformWarning
def test_context_combines_with_ca_certs(self):
ctx = util.ssl_.create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED)
@@ -249,11 +249,11 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self.addCleanup(https_pool.close)
conn = https_pool._new_conn()
- self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
+ assert conn.__class__ == VerifiedHTTPSConnection
with mock.patch("warnings.warn") as warn:
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# Modern versions of Python, or systems using PyOpenSSL, don't
# emit warnings.
@@ -262,15 +262,15 @@ class TestHTTPS(HTTPSDummyServerTestCase):
or util.IS_PYOPENSSL
or util.IS_SECURETRANSPORT
):
- self.assertFalse(warn.called, warn.call_args_list)
+ assert not warn.called, warn.call_args_list
else:
- self.assertTrue(warn.called)
+ assert warn.called
if util.HAS_SNI:
call = warn.call_args_list[0]
else:
call = warn.call_args_list[1]
error = call[0][1]
- self.assertEqual(error, InsecurePlatformWarning)
+ assert error == InsecurePlatformWarning
@onlyPy279OrNewer
@notSecureTransport # SecureTransport does not support cert directories
@@ -282,12 +282,12 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self.addCleanup(https_pool.close)
conn = https_pool._new_conn()
- self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
+ assert conn.__class__ == VerifiedHTTPSConnection
with mock.patch("warnings.warn") as warn:
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
- self.assertFalse(warn.called, warn.call_args_list)
+ assert r.status == 200
+ assert not warn.called, warn.call_args_list
def test_invalid_common_name(self):
https_pool = HTTPSConnectionPool(
@@ -299,11 +299,10 @@ class TestHTTPS(HTTPSDummyServerTestCase):
https_pool.request("GET", "/")
self.fail("Didn't raise SSL invalid common name")
except MaxRetryError as e:
- self.assertIsInstance(e.reason, SSLError)
- self.assertTrue(
- "doesn't match" in str(e.reason)
- or "certificate verify failed" in str(e.reason)
- )
+ assert isinstance(e.reason, SSLError)
+ assert "doesn't match" in str(
+ e.reason
+ ) or "certificate verify failed" in str(e.reason)
def test_verified_with_bad_ca_certs(self):
https_pool = HTTPSConnectionPool(
@@ -315,11 +314,9 @@ class TestHTTPS(HTTPSDummyServerTestCase):
https_pool.request("GET", "/")
self.fail("Didn't raise SSL error with bad CA certs")
except MaxRetryError as e:
- self.assertIsInstance(e.reason, SSLError)
- self.assertIn(
- "certificate verify failed",
- str(e.reason),
- "Expected 'certificate verify failed'," "instead got: %r" % e.reason,
+ assert isinstance(e.reason, SSLError)
+ assert "certificate verify failed" in str(e.reason), (
+ "Expected 'certificate verify failed'," "instead got: %r" % e.reason
)
def test_verified_without_ca_certs(self):
@@ -335,27 +332,29 @@ class TestHTTPS(HTTPSDummyServerTestCase):
"Didn't raise SSL error with no CA certs when" "CERT_REQUIRED is set"
)
except MaxRetryError as e:
- self.assertIsInstance(e.reason, SSLError)
+ assert isinstance(e.reason, SSLError)
# there is a different error message depending on whether or
# not pyopenssl is injected
- self.assertTrue(
+ assert (
"No root certificates specified" in str(e.reason)
or "certificate verify failed" in str(e.reason)
- or "invalid certificate chain" in str(e.reason),
+ or "invalid certificate chain" in str(e.reason)
+ ), (
"Expected 'No root certificates specified', "
"'certificate verify failed', or "
"'invalid certificate chain', "
- "instead got: %r" % e.reason,
+ "instead got: %r" % e.reason
)
def test_no_ssl(self):
pool = HTTPSConnectionPool(self.host, self.port)
pool.ConnectionCls = None
self.addCleanup(pool.close)
- self.assertRaises(SSLError, pool._new_conn)
- with self.assertRaises(MaxRetryError) as cm:
+ with pytest.raises(SSLError):
+ pool._new_conn()
+ with pytest.raises(MaxRetryError) as cm:
pool.request("GET", "/", retries=0)
- self.assertIsInstance(cm.exception.reason, SSLError)
+ assert isinstance(cm.value.reason, SSLError)
def test_unverified_ssl(self):
""" Test that bare HTTPSConnection can connect, make requests """
@@ -364,14 +363,14 @@ class TestHTTPS(HTTPSDummyServerTestCase):
with mock.patch("warnings.warn") as warn:
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200)
- self.assertTrue(warn.called)
+ assert r.status == 200
+ assert warn.called
# Modern versions of Python, or systems using PyOpenSSL, only emit
# the unverified warning. Older systems may also emit other
# warnings, which we want to ignore here.
calls = warn.call_args_list
- self.assertIn(InsecureRequestWarning, [x[0][1] for x in calls])
+ assert InsecureRequestWarning in [x[0][1] for x in calls]
def test_ssl_unverified_with_ca_certs(self):
pool = HTTPSConnectionPool(
@@ -381,8 +380,8 @@ class TestHTTPS(HTTPSDummyServerTestCase):
with mock.patch("warnings.warn") as warn:
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200)
- self.assertTrue(warn.called)
+ assert r.status == 200
+ assert warn.called
# Modern versions of Python, or systems using PyOpenSSL, only emit
# the unverified warning. Older systems may also emit other
@@ -398,7 +397,7 @@ class TestHTTPS(HTTPSDummyServerTestCase):
category = calls[1][0][1]
else:
category = calls[2][0][1]
- self.assertEqual(category, InsecureRequestWarning)
+ assert category == InsecureRequestWarning
def test_assert_hostname_false(self):
https_pool = HTTPSConnectionPool(
@@ -436,7 +435,7 @@ class TestHTTPS(HTTPSDummyServerTestCase):
# socket, so only add this assertion if the attribute is there (i.e.
# the python ssl module).
if hasattr(conn.sock, "server_hostname"):
- self.assertEqual(conn.sock.server_hostname, "localhost")
+ assert conn.sock.server_hostname == "localhost"
def test_assert_fingerprint_md5(self):
https_pool = HTTPSConnectionPool(
@@ -485,9 +484,9 @@ class TestHTTPS(HTTPSDummyServerTestCase):
)
def _test_request(pool):
- with self.assertRaises(MaxRetryError) as cm:
+ with pytest.raises(MaxRetryError) as cm:
pool.request("GET", "/", retries=0)
- self.assertIsInstance(cm.exception.reason, SSLError)
+ assert isinstance(cm.value.reason, SSLError)
_test_request(https_pool)
https_pool._get_conn()
@@ -510,9 +509,9 @@ class TestHTTPS(HTTPSDummyServerTestCase):
https_pool.assert_fingerprint = (
"AA:AA:AA:AA:AA:AAAA:AA:AAAA:AA:" "AA:AA:AA:AA:AA:AA:AA:AA:AA"
)
- with self.assertRaises(MaxRetryError) as cm:
+ with pytest.raises(MaxRetryError) as cm:
https_pool.request("GET", "/", retries=0)
- self.assertIsInstance(cm.exception.reason, SSLError)
+ assert isinstance(cm.value.reason, SSLError)
def test_verify_none_and_good_fingerprint(self):
https_pool = HTTPSConnectionPool(
@@ -562,7 +561,8 @@ class TestHTTPS(HTTPSDummyServerTestCase):
cert_reqs="CERT_REQUIRED",
)
self.addCleanup(https_pool.close)
- self.assertRaises(ConnectTimeoutError, https_pool.request, "GET", "/")
+ with pytest.raises(ConnectTimeoutError):
+ https_pool.request("GET", "/")
timeout = Timeout(read=0.01)
https_pool = HTTPSConnectionPool(
@@ -614,30 +614,20 @@ class TestHTTPS(HTTPSDummyServerTestCase):
https_pool = new_pool(Timeout(connect=0.001))
conn = https_pool._new_conn()
- self.assertRaises(ConnectTimeoutError, https_pool.request, "GET", "/")
- self.assertRaises(
- ConnectTimeoutError, https_pool._make_request, conn, "GET", "/"
- )
+ with pytest.raises(ConnectTimeoutError):
+ https_pool.request("GET", "/")
+ with pytest.raises(ConnectTimeoutError):
+ https_pool._make_request(conn, "GET", "/")
https_pool = new_pool(Timeout(connect=5))
- self.assertRaises(
- ConnectTimeoutError,
- https_pool.request,
- "GET",
- "/",
- timeout=Timeout(connect=0.001),
- )
+ with pytest.raises(ConnectTimeoutError):
+ https_pool.request("GET", "/", timeout=Timeout(connect=0.001))
t = Timeout(total=None)
https_pool = new_pool(t)
conn = https_pool._new_conn()
- self.assertRaises(
- ConnectTimeoutError,
- https_pool.request,
- "GET",
- "/",
- timeout=Timeout(total=None, connect=0.001),
- )
+ with pytest.raises(ConnectTimeoutError):
+ https_pool.request("GET", "/", timeout=Timeout(total=None, connect=0.001))
def test_enhanced_ssl_connection(self):
fingerprint = "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A"
@@ -660,7 +650,7 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self._pool.ca_certs = DEFAULT_CA
w = self._request_without_resource_warnings("GET", "/")
- self.assertEqual([], w)
+ assert [] == w
@onlyPy279OrNewer
def test_ssl_wrong_system_time(self):
@@ -671,11 +661,11 @@ class TestHTTPS(HTTPSDummyServerTestCase):
w = self._request_without_resource_warnings("GET", "/")
- self.assertEqual(len(w), 1)
+ assert len(w) == 1
warning = w[0]
- self.assertEqual(SystemTimeWarning, warning.category)
- self.assertIn(str(RECENT_DATE), warning.message.args[0])
+ assert SystemTimeWarning == warning.category
+ assert str(RECENT_DATE) in warning.message.args[0]
def _request_without_resource_warnings(self, method, url):
with warnings.catch_warnings(record=True) as w:
@@ -690,12 +680,12 @@ class TestHTTPS(HTTPSDummyServerTestCase):
self._pool.ssl_version = self.certs["ssl_version"]
r = self._pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
def test_set_cert_default_cert_required(self):
conn = VerifiedHTTPSConnection(self.host, self.port)
conn.set_cert()
- self.assertEqual(conn.cert_reqs, ssl.CERT_REQUIRED)
+ assert conn.cert_reqs == ssl.CERT_REQUIRED
def test_tls_protocol_name_of_socket(self):
if self.tls_protocol_name is None:
@@ -707,7 +697,7 @@ class TestHTTPS(HTTPSDummyServerTestCase):
if not hasattr(conn.sock, "version"):
pytest.skip("SSLSocket.version() not available")
- self.assertEqual(conn.sock.version(), self.tls_protocol_name)
+ assert conn.sock.version() == self.tls_protocol_name
@requiresTLSv1()
@@ -745,8 +735,8 @@ class TestHTTPS_NoSAN(HTTPSDummyServerTestCase):
)
self.addCleanup(https_pool.close)
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
- self.assertTrue(warn.called)
+ assert r.status == 200
+ assert warn.called
class TestHTTPS_IPSAN(HTTPSDummyServerTestCase):
@@ -764,7 +754,7 @@ class TestHTTPS_IPSAN(HTTPSDummyServerTestCase):
)
self.addCleanup(https_pool.close)
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
class TestHTTPS_IPv6Addr(IPV6HTTPSDummyServerTestCase):
@@ -778,7 +768,7 @@ class TestHTTPS_IPv6Addr(IPV6HTTPSDummyServerTestCase):
)
self.addCleanup(https_pool.close)
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
class TestHTTPS_IPV6SAN(IPV6HTTPSDummyServerTestCase):
@@ -796,7 +786,7 @@ class TestHTTPS_IPV6SAN(IPV6HTTPSDummyServerTestCase):
)
self.addCleanup(https_pool.close)
r = https_pool.request("GET", "/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
if __name__ == "__main__":
diff --git a/test/with_dummyserver/test_no_ssl.py b/test/with_dummyserver/test_no_ssl.py
index c8435fa8..a3cb63ca 100644
--- a/test/with_dummyserver/test_no_ssl.py
+++ b/test/with_dummyserver/test_no_ssl.py
@@ -15,7 +15,7 @@ class TestHTTPWithoutSSL(HTTPDummyServerTestCase, TestWithoutSSL):
pool = urllib3.HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
r = pool.request("GET", "/")
- self.assertEqual(r.status, 200, r.data)
+ assert r.status == 200, r.data
class TestHTTPSWithoutSSL(HTTPSDummyServerTestCase, TestWithoutSSL):
@@ -25,4 +25,4 @@ class TestHTTPSWithoutSSL(HTTPSDummyServerTestCase, TestWithoutSSL):
try:
pool.request("GET", "/")
except urllib3.exceptions.SSLError as e:
- self.assertIn("SSL module is not available", str(e))
+ assert "SSL module is not available" in str(e)
diff --git a/test/with_dummyserver/test_poolmanager.py b/test/with_dummyserver/test_poolmanager.py
index 90a36363..14143e4f 100644
--- a/test/with_dummyserver/test_poolmanager.py
+++ b/test/with_dummyserver/test_poolmanager.py
@@ -27,7 +27,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
redirect=False,
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = http.request(
"GET",
@@ -35,8 +35,8 @@ class TestPoolManager(HTTPDummyServerTestCase):
fields={"target": "%s/" % self.base_url},
)
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_redirect_twice(self):
http = PoolManager()
@@ -49,7 +49,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
redirect=False,
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = http.request(
"GET",
@@ -59,8 +59,8 @@ class TestPoolManager(HTTPDummyServerTestCase):
},
)
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_redirect_to_relative_url(self):
http = PoolManager()
@@ -73,14 +73,14 @@ class TestPoolManager(HTTPDummyServerTestCase):
redirect=False,
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = http.request(
"GET", "%s/redirect" % self.base_url, fields={"target": "/redirect"}
)
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_cross_host_redirect(self):
http = PoolManager()
@@ -110,7 +110,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
retries=1,
)
- self.assertEqual(r._pool.host, self.host_alt)
+ assert r._pool.host == self.host_alt
def test_too_many_redirects(self):
http = PoolManager()
@@ -153,11 +153,11 @@ class TestPoolManager(HTTPDummyServerTestCase):
headers={"Authorization": "foo"},
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
data = json.loads(r.data.decode("utf-8"))
- self.assertNotIn("Authorization", data)
+ assert "Authorization" not in data
r = http.request(
"GET",
@@ -166,12 +166,12 @@ class TestPoolManager(HTTPDummyServerTestCase):
headers={"authorization": "foo"},
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
data = json.loads(r.data.decode("utf-8"))
- self.assertNotIn("authorization", data)
- self.assertNotIn("Authorization", data)
+ assert "authorization" not in data
+ assert "Authorization" not in data
def test_redirect_cross_host_no_remove_headers(self):
http = PoolManager()
@@ -185,11 +185,11 @@ class TestPoolManager(HTTPDummyServerTestCase):
retries=Retry(remove_headers_on_redirect=[]),
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
data = json.loads(r.data.decode("utf-8"))
- self.assertEqual(data["Authorization"], "foo")
+ assert data["Authorization"] == "foo"
def test_redirect_cross_host_set_removed_headers(self):
http = PoolManager()
@@ -203,12 +203,12 @@ class TestPoolManager(HTTPDummyServerTestCase):
retries=Retry(remove_headers_on_redirect=["X-API-Secret"]),
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
data = json.loads(r.data.decode("utf-8"))
- self.assertNotIn("X-API-Secret", data)
- self.assertEqual(data["Authorization"], "bar")
+ assert "X-API-Secret" not in data
+ assert data["Authorization"] == "bar"
r = http.request(
"GET",
@@ -218,13 +218,13 @@ class TestPoolManager(HTTPDummyServerTestCase):
retries=Retry(remove_headers_on_redirect=["X-API-Secret"]),
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
data = json.loads(r.data.decode("utf-8"))
- self.assertNotIn("x-api-secret", data)
- self.assertNotIn("X-API-Secret", data)
- self.assertEqual(data["Authorization"], "bar")
+ assert "x-api-secret" not in data
+ assert "X-API-Secret" not in data
+ assert data["Authorization"] == "bar"
def test_raise_on_redirect(self):
http = PoolManager()
@@ -239,7 +239,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
retries=Retry(total=None, redirect=1, raise_on_redirect=False),
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
def test_raise_on_status(self):
http = PoolManager()
@@ -281,7 +281,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
),
)
- self.assertEqual(r.status, 500)
+ assert r.status == 500
def test_missing_port(self):
# Can a URL that lacks an explicit port like ':80' succeed, or
@@ -299,8 +299,8 @@ class TestPoolManager(HTTPDummyServerTestCase):
finally:
port_by_scheme["http"] = 80
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_headers(self):
http = PoolManager(headers={"Foo": "bar"})
@@ -308,47 +308,47 @@ class TestPoolManager(HTTPDummyServerTestCase):
r = http.request("GET", "%s/headers" % self.base_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
+ assert returned_headers.get("Foo") == "bar"
r = http.request("POST", "%s/headers" % self.base_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
+ assert returned_headers.get("Foo") == "bar"
r = http.request_encode_url("GET", "%s/headers" % self.base_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
+ assert returned_headers.get("Foo") == "bar"
r = http.request_encode_body("POST", "%s/headers" % self.base_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
+ assert returned_headers.get("Foo") == "bar"
r = http.request_encode_url(
"GET", "%s/headers" % self.base_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
r = http.request_encode_body(
"GET", "%s/headers" % self.base_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
def test_http_with_ssl_keywords(self):
http = PoolManager(ca_certs="REQUIRED")
self.addCleanup(http.clear)
r = http.request("GET", "http://%s:%s/" % (self.host, self.port))
- self.assertEqual(r.status, 200)
+ assert r.status == 200
def test_http_with_ca_cert_dir(self):
http = PoolManager(ca_certs="REQUIRED", ca_cert_dir="/nosuchdir")
self.addCleanup(http.clear)
r = http.request("GET", "http://%s:%s/" % (self.host, self.port))
- self.assertEqual(r.status, 200)
+ assert r.status == 200
@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not supported on this system")
diff --git a/test/with_dummyserver/test_proxy_poolmanager.py b/test/with_dummyserver/test_proxy_poolmanager.py
index f19391fb..4c4e506d 100644
--- a/test/with_dummyserver/test_proxy_poolmanager.py
+++ b/test/with_dummyserver/test_proxy_poolmanager.py
@@ -27,10 +27,10 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
self.addCleanup(http.clear)
r = http.request("GET", "%s/" % self.http_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
r = http.request("GET", "%s/" % self.https_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
def test_nagle_proxy(self):
""" Test that proxy connections do not have TCP_NODELAY turned on """
@@ -43,37 +43,35 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
tcp_nodelay_setting = conn.sock.getsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY
)
- self.assertEqual(
- tcp_nodelay_setting,
- 0,
- (
- "Expected TCP_NODELAY for proxies to be set "
- "to zero, instead was %s" % tcp_nodelay_setting
- ),
+ assert tcp_nodelay_setting == 0, (
+ "Expected TCP_NODELAY for proxies to be set "
+ "to zero, instead was %s" % tcp_nodelay_setting
)
def test_proxy_conn_fail(self):
host, port = get_unreachable_address()
http = proxy_from_url("http://%s:%s/" % (host, port), retries=1, timeout=0.05)
self.addCleanup(http.clear)
- self.assertRaises(MaxRetryError, http.request, "GET", "%s/" % self.https_url)
- self.assertRaises(MaxRetryError, http.request, "GET", "%s/" % self.http_url)
+ with pytest.raises(MaxRetryError):
+ http.request("GET", "%s/" % self.https_url)
+ with pytest.raises(MaxRetryError):
+ http.request("GET", "%s/" % self.http_url)
try:
http.request("GET", "%s/" % self.http_url)
self.fail("Failed to raise retry error.")
except MaxRetryError as e:
- self.assertEqual(type(e.reason), ProxyError)
+ assert type(e.reason) == ProxyError
def test_oldapi(self):
http = ProxyManager(connection_from_url(self.proxy_url), ca_certs=DEFAULT_CA)
self.addCleanup(http.clear)
r = http.request("GET", "%s/" % self.http_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
r = http.request("GET", "%s/" % self.https_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
def test_proxy_verified(self):
http = proxy_from_url(
@@ -85,18 +83,16 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
https_pool.request("GET", "/", retries=0)
self.fail("Didn't raise SSL error with wrong CA")
except MaxRetryError as e:
- self.assertIsInstance(e.reason, SSLError)
- self.assertIn(
- "certificate verify failed",
- str(e.reason),
- "Expected 'certificate verify failed'," "instead got: %r" % e.reason,
+ assert isinstance(e.reason, SSLError)
+ assert "certificate verify failed" in str(e.reason), (
+ "Expected 'certificate verify failed'," "instead got: %r" % e.reason
)
http = proxy_from_url(self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA)
https_pool = http._new_pool("https", self.https_host, self.https_port)
conn = https_pool._new_conn()
- self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
+ assert conn.__class__ == VerifiedHTTPSConnection
https_pool.request("GET", "/") # Should succeed without exceptions.
http = proxy_from_url(self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA)
@@ -106,8 +102,8 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
https_fail_pool.request("GET", "/", retries=0)
self.fail("Didn't raise SSL invalid common name")
except MaxRetryError as e:
- self.assertIsInstance(e.reason, SSLError)
- self.assertIn("doesn't match", str(e.reason))
+ assert isinstance(e.reason, SSLError)
+ assert "doesn't match" in str(e.reason)
def test_redirect(self):
http = proxy_from_url(self.proxy_url)
@@ -120,7 +116,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
redirect=False,
)
- self.assertEqual(r.status, 303)
+ assert r.status == 303
r = http.request(
"GET",
@@ -128,8 +124,8 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
fields={"target": "%s/" % self.http_url},
)
- self.assertEqual(r.status, 200)
- self.assertEqual(r.data, b"Dummy server!")
+ assert r.status == 200
+ assert r.data == b"Dummy server!"
def test_cross_host_redirect(self):
http = proxy_from_url(self.proxy_url)
@@ -156,7 +152,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
timeout=1,
retries=1,
)
- self.assertNotEqual(r._pool.host, self.http_host_alt)
+ assert r._pool.host != self.http_host_alt
def test_cross_protocol_redirect(self):
http = proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA)
@@ -183,7 +179,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
timeout=1,
retries=1,
)
- self.assertEqual(r._pool.host, self.https_host)
+ assert r._pool.host == self.https_host
def test_headers(self):
http = proxy_from_url(
@@ -196,78 +192,86 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
r = http.request_encode_url("GET", "%s/headers" % self.http_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
- self.assertEqual(returned_headers.get("Hickory"), "dickory")
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.http_host, self.http_port)
+ assert returned_headers.get("Foo") == "bar"
+ assert returned_headers.get("Hickory") == "dickory"
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.http_host,
+ self.http_port,
)
r = http.request_encode_url("GET", "%s/headers" % self.http_url_alt)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
- self.assertEqual(returned_headers.get("Hickory"), "dickory")
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.http_host_alt, self.http_port)
+ assert returned_headers.get("Foo") == "bar"
+ assert returned_headers.get("Hickory") == "dickory"
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.http_host_alt,
+ self.http_port,
)
r = http.request_encode_url("GET", "%s/headers" % self.https_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
- self.assertIsNone(returned_headers.get("Hickory"))
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.https_host, self.https_port)
+ assert returned_headers.get("Foo") == "bar"
+ assert returned_headers.get("Hickory") is None
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.https_host,
+ self.https_port,
)
r = http.request_encode_body("POST", "%s/headers" % self.http_url)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
- self.assertEqual(returned_headers.get("Hickory"), "dickory")
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.http_host, self.http_port)
+ assert returned_headers.get("Foo") == "bar"
+ assert returned_headers.get("Hickory") == "dickory"
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.http_host,
+ self.http_port,
)
r = http.request_encode_url(
"GET", "%s/headers" % self.http_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
- self.assertEqual(returned_headers.get("Hickory"), "dickory")
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.http_host, self.http_port)
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
+ assert returned_headers.get("Hickory") == "dickory"
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.http_host,
+ self.http_port,
)
r = http.request_encode_url(
"GET", "%s/headers" % self.https_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
- self.assertIsNone(returned_headers.get("Hickory"))
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.https_host, self.https_port)
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
+ assert returned_headers.get("Hickory") is None
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.https_host,
+ self.https_port,
)
r = http.request_encode_body(
"GET", "%s/headers" % self.http_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
- self.assertEqual(returned_headers.get("Hickory"), "dickory")
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.http_host, self.http_port)
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
+ assert returned_headers.get("Hickory") == "dickory"
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.http_host,
+ self.http_port,
)
r = http.request_encode_body(
"GET", "%s/headers" % self.https_url, headers={"Baz": "quux"}
)
returned_headers = json.loads(r.data.decode())
- self.assertIsNone(returned_headers.get("Foo"))
- self.assertEqual(returned_headers.get("Baz"), "quux")
- self.assertIsNone(returned_headers.get("Hickory"))
- self.assertEqual(
- returned_headers.get("Host"), "%s:%s" % (self.https_host, self.https_port)
+ assert returned_headers.get("Foo") is None
+ assert returned_headers.get("Baz") == "quux"
+ assert returned_headers.get("Hickory") is None
+ assert returned_headers.get("Host") == "%s:%s" % (
+ self.https_host,
+ self.https_port,
)
def test_headerdict(self):
@@ -283,8 +287,8 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
request_headers = HTTPHeaderDict(baz="quux")
r = http.request("GET", "%s/headers" % self.http_url, headers=request_headers)
returned_headers = json.loads(r.data.decode())
- self.assertEqual(returned_headers.get("Foo"), "bar")
- self.assertEqual(returned_headers.get("Baz"), "quux")
+ assert returned_headers.get("Foo") == "bar"
+ assert returned_headers.get("Baz") == "quux"
def test_proxy_pooling(self):
http = proxy_from_url(self.proxy_url, cert_reqs="NONE")
@@ -292,19 +296,19 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
for x in range(2):
http.urlopen("GET", self.http_url)
- self.assertEqual(len(http.pools), 1)
+ assert len(http.pools) == 1
for x in range(2):
http.urlopen("GET", self.http_url_alt)
- self.assertEqual(len(http.pools), 1)
+ assert len(http.pools) == 1
for x in range(2):
http.urlopen("GET", self.https_url)
- self.assertEqual(len(http.pools), 2)
+ assert len(http.pools) == 2
for x in range(2):
http.urlopen("GET", self.https_url_alt)
- self.assertEqual(len(http.pools), 3)
+ assert len(http.pools) == 3
def test_proxy_pooling_ext(self):
http = proxy_from_url(self.proxy_url)
@@ -314,9 +318,9 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
hc2 = http.connection_from_host(self.http_host, self.http_port)
hc3 = http.connection_from_url(self.http_url_alt)
hc4 = http.connection_from_host(self.http_host_alt, self.http_port)
- self.assertEqual(hc1, hc2)
- self.assertEqual(hc2, hc3)
- self.assertEqual(hc3, hc4)
+ assert hc1 == hc2
+ assert hc2 == hc3
+ assert hc3 == hc4
sc1 = http.connection_from_url(self.https_url)
sc2 = http.connection_from_host(
@@ -326,9 +330,9 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
sc4 = http.connection_from_host(
self.https_host_alt, self.https_port, scheme="https"
)
- self.assertEqual(sc1, sc2)
- self.assertNotEqual(sc2, sc3)
- self.assertEqual(sc3, sc4)
+ assert sc1 == sc2
+ assert sc2 != sc3
+ assert sc3 == sc4
@pytest.mark.timeout(0.5)
@requires_network
@@ -339,7 +343,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
https.request("GET", self.http_url, timeout=0.001)
self.fail("Failed to raise retry error.")
except MaxRetryError as e:
- self.assertEqual(type(e.reason), ConnectTimeoutError)
+ assert type(e.reason) == ConnectTimeoutError
@pytest.mark.timeout(0.5)
@requires_network
@@ -350,7 +354,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
https.request("GET", self.http_url)
self.fail("Failed to raise retry error.")
except MaxRetryError as e:
- self.assertEqual(type(e.reason), ConnectTimeoutError)
+ assert type(e.reason) == ConnectTimeoutError
def test_scheme_host_case_insensitive(self):
"""Assert that upper-case schemes and hosts are normalized."""
@@ -358,10 +362,10 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
self.addCleanup(http.clear)
r = http.request("GET", "%s/" % self.http_url.upper())
- self.assertEqual(r.status, 200)
+ assert r.status == 200
r = http.request("GET", "%s/" % self.https_url.upper())
- self.assertEqual(r.status, 200)
+ assert r.status == 200
class TestIPv6HTTPProxyManager(IPv6HTTPDummyProxyTestCase):
@@ -377,10 +381,10 @@ class TestIPv6HTTPProxyManager(IPv6HTTPDummyProxyTestCase):
self.addCleanup(http.clear)
r = http.request("GET", "%s/" % self.http_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
r = http.request("GET", "%s/" % self.https_url)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
if __name__ == "__main__":
diff --git a/test/with_dummyserver/test_socketlevel.py b/test/with_dummyserver/test_socketlevel.py
index 76637a38..a62fa916 100644
--- a/test/with_dummyserver/test_socketlevel.py
+++ b/test/with_dummyserver/test_socketlevel.py
@@ -69,8 +69,8 @@ class TestCookies(SocketDummyServerTestCase):
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
r = pool.request("GET", "/", retries=0)
- self.assertEqual(r.headers, {"set-cookie": "foo=1, bar=1"})
- self.assertEqual(r.headers.getlist("set-cookie"), ["foo=1", "bar=1"])
+ assert r.headers == {"set-cookie": "foo=1, bar=1"}
+ assert r.headers.getlist("set-cookie") == ["foo=1", "bar=1"]
class TestSNI(SocketDummyServerTestCase):
@@ -94,9 +94,9 @@ class TestSNI(SocketDummyServerTestCase):
except MaxRetryError: # We are violating the protocol
pass
done_receiving.wait()
- self.assertIn(
- self.host.encode("ascii"), self.buf, "missing hostname in SSL handshake"
- )
+ assert (
+ self.host.encode("ascii") in self.buf
+ ), "missing hostname in SSL handshake"
class TestClientCerts(SocketDummyServerTestCase):
@@ -161,7 +161,7 @@ class TestClientCerts(SocketDummyServerTestCase):
pool.request("GET", "/", retries=0)
done_receiving.set()
- self.assertEqual(len(client_certs), 1)
+ assert len(client_certs) == 1
def test_client_certs_one_file(self):
"""
@@ -205,7 +205,7 @@ class TestClientCerts(SocketDummyServerTestCase):
pool.request("GET", "/", retries=0)
done_receiving.set()
- self.assertEqual(len(client_certs), 1)
+ assert len(client_certs) == 1
def test_missing_client_certs_raises_error(self):
"""
@@ -296,7 +296,7 @@ class TestClientCerts(SocketDummyServerTestCase):
pool.request("GET", "/", retries=0)
done_receiving.set()
- self.assertEqual(len(client_certs), 1)
+ assert len(client_certs) == 1
@requires_ssl_context_keyfile_password
def test_load_keyfile_with_invalid_password(self):
@@ -353,24 +353,23 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
response = pool.request("GET", "/", retries=0)
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"Response 0")
+ assert response.status == 200
+ assert response.data == b"Response 0"
done_closing.wait() # wait until the socket in our pool gets closed
response = pool.request("GET", "/", retries=0)
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"Response 1")
+ assert response.status == 200
+ assert response.data == b"Response 1"
def test_connection_refused(self):
# Does the pool retry if there is no listener on the port?
host, port = get_unreachable_address()
http = HTTPConnectionPool(host, port, maxsize=3, block=True)
self.addCleanup(http.close)
- self.assertRaises(
- MaxRetryError, http.request, "GET", "/", retries=0, release_conn=False
- )
- self.assertEqual(http.pool.qsize(), http.pool.maxsize)
+ with pytest.raises(MaxRetryError):
+ http.request("GET", "/", retries=0, release_conn=False)
+ assert http.pool.qsize() == http.pool.maxsize
def test_connection_read_timeout(self):
timed_out = Event()
@@ -390,13 +389,12 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(http.close)
try:
- self.assertRaises(
- ReadTimeoutError, http.request, "GET", "/", release_conn=False
- )
+ with pytest.raises(ReadTimeoutError):
+ http.request("GET", "/", release_conn=False)
finally:
timed_out.set()
- self.assertEqual(http.pool.qsize(), http.pool.maxsize)
+ assert http.pool.qsize() == http.pool.maxsize
def test_read_timeout_dont_retry_method_not_in_whitelist(self):
timed_out = Event()
@@ -412,7 +410,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
try:
- self.assertRaises(ReadTimeoutError, pool.request, "POST", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("POST", "/")
finally:
timed_out.set()
@@ -432,7 +431,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
pool = HTTPSConnectionPool(self.host, self.port, timeout=0.01, retries=False)
self.addCleanup(pool.close)
try:
- self.assertRaises(ReadTimeoutError, pool.request, "GET", "/")
+ with pytest.raises(ReadTimeoutError):
+ pool.request("GET", "/")
finally:
timed_out.set()
@@ -477,8 +477,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
response = pool.request("GET", "/", retries=1)
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"Response 2")
+ assert response.status == 200
+ assert response.data == b"Response 2"
finally:
socket.setdefaulttimeout(default_timeout)
@@ -516,7 +516,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
timeout=Timeout(connect=1, read=0.01),
)
try:
- self.assertRaises(ReadTimeoutError, response.read)
+ with pytest.raises(ReadTimeoutError):
+ response.read()
finally:
timed_out.set()
@@ -546,14 +547,10 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
try:
- self.assertRaises(
- ReadTimeoutError,
- pool.urlopen,
- "GET",
- "/",
- retries=False,
- timeout=Timeout(connect=1, read=0.01),
- )
+ with pytest.raises(ReadTimeoutError):
+ pool.urlopen(
+ "GET", "/", retries=False, timeout=Timeout(connect=1, read=0.01)
+ )
finally:
timed_out.set()
@@ -586,7 +583,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
response = pool.request("GET", "/", retries=0, preload_content=False)
- self.assertRaises(ProtocolError, response.read)
+ with pytest.raises(ProtocolError):
+ response.read()
def test_retry_weird_http_version(self):
""" Retry class should handle httplib.BadStatusLine errors properly """
@@ -636,8 +634,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
retry = Retry(read=1)
response = pool.request("GET", "/", retries=retry)
- self.assertEqual(response.status, 200)
- self.assertEqual(response.data, b"foo")
+ assert response.status == 200
+ assert response.data == b"foo"
def test_connection_cleanup_on_read_timeout(self):
timed_out = Event()
@@ -671,8 +669,9 @@ class TestSocketClosing(SocketDummyServerTestCase):
timeout=Timeout(connect=1, read=0.01),
)
try:
- self.assertRaises(ReadTimeoutError, response.read)
- self.assertEqual(poolsize, pool.pool.qsize())
+ with pytest.raises(ReadTimeoutError):
+ response.read()
+ assert poolsize == pool.pool.qsize()
finally:
timed_out.set()
@@ -705,8 +704,9 @@ class TestSocketClosing(SocketDummyServerTestCase):
poolsize = pool.pool.qsize()
response = pool.request("GET", "/", retries=0, preload_content=False)
- self.assertRaises(ProtocolError, response.read)
- self.assertEqual(poolsize, pool.pool.qsize())
+ with pytest.raises(ProtocolError):
+ response.read()
+ assert poolsize == pool.pool.qsize()
def test_connection_closed_on_read_timeout_preload_false(self):
timed_out = Event()
@@ -772,7 +772,8 @@ class TestSocketClosing(SocketDummyServerTestCase):
timeout=Timeout(connect=1, read=0.1),
)
try:
- self.assertRaises(ReadTimeoutError, response.read)
+ with pytest.raises(ReadTimeoutError):
+ response.read()
finally:
timed_out.set()
@@ -784,7 +785,7 @@ class TestSocketClosing(SocketDummyServerTestCase):
preload_content=False,
timeout=Timeout(connect=1, read=1),
)
- self.assertEqual(len(response.read()), 8)
+ assert len(response.read()) == 8
def test_closing_response_actually_closes_connection(self):
done_closing = Event()
@@ -813,7 +814,7 @@ class TestSocketClosing(SocketDummyServerTestCase):
# Don't get stuck in a timeout.
sock.settimeout(1)
new_data = sock.recv(65536)
- self.assertFalse(new_data)
+ assert not new_data
sock.close()
complete.set()
@@ -822,7 +823,7 @@ class TestSocketClosing(SocketDummyServerTestCase):
self.addCleanup(pool.close)
response = pool.request("GET", "/", retries=0, preload_content=False)
- self.assertEqual(response.status, 200)
+ assert response.status == 200
response.close()
done_closing.set() # wait until the socket in our pool gets closed
@@ -890,14 +891,14 @@ class TestSocketClosing(SocketDummyServerTestCase):
# The connection should still be on the response object, and none
# should be in the pool. We opened two though.
- self.assertEqual(pool.num_connections, 2)
- self.assertEqual(pool.pool.qsize(), 0)
- self.assertIsNotNone(response.connection)
+ assert pool.num_connections == 2
+ assert pool.pool.qsize() == 0
+ assert response.connection is not None
# Consume the data. This should put the connection back.
response.read()
- self.assertEqual(pool.pool.qsize(), 1)
- self.assertIsNone(response.connection)
+ assert pool.pool.qsize() == 1
+ assert response.connection is None
class TestProxyManager(SocketDummyServerTestCase):
@@ -927,22 +928,19 @@ class TestProxyManager(SocketDummyServerTestCase):
r = proxy.request("GET", "http://google.com/")
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
- self.assertEqual(
- sorted(r.data.split(b"\r\n")),
- sorted(
- [
- b"GET http://google.com/ HTTP/1.1",
- b"Host: google.com",
- b"Accept-Encoding: identity",
- b"Accept: */*",
- b"",
- b"",
- ]
- ),
+ assert sorted(r.data.split(b"\r\n")) == sorted(
+ [
+ b"GET http://google.com/ HTTP/1.1",
+ b"Host: google.com",
+ b"Accept-Encoding: identity",
+ b"Accept: */*",
+ b"",
+ b"",
+ ]
)
def test_headers(self):
@@ -976,11 +974,11 @@ class TestProxyManager(SocketDummyServerTestCase):
r = conn.urlopen("GET", "http://www.google.com/", assert_same_host=False)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
- self.assertIn(b"For The Proxy: YEAH!\r\n", r.data)
+ assert b"For The Proxy: YEAH!\r\n" in r.data
def test_retries(self):
close_event = Event()
@@ -1019,17 +1017,13 @@ class TestProxyManager(SocketDummyServerTestCase):
r = conn.urlopen(
"GET", "http://www.google.com", assert_same_host=False, retries=1
)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
close_event.wait(timeout=1)
- self.assertRaises(
- ProxyError,
- conn.urlopen,
- "GET",
- "http://www.google.com",
- assert_same_host=False,
- retries=False,
- )
+ with pytest.raises(ProxyError):
+ conn.urlopen(
+ "GET", "http://www.google.com", assert_same_host=False, retries=False
+ )
def test_connect_reconn(self):
def proxy_ssl_one(listener):
@@ -1091,9 +1085,9 @@ class TestProxyManager(SocketDummyServerTestCase):
url = "https://{0}".format(self.host)
conn = proxy.connection_from_url(url)
r = conn.urlopen("GET", url, retries=0)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
r = conn.urlopen("GET", url, retries=0)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
def test_connect_ipv6_addr(self):
ipv6_addr = "2001:4998:c:a06::2:4008"
@@ -1140,7 +1134,7 @@ class TestProxyManager(SocketDummyServerTestCase):
conn = proxy.connection_from_url(url)
try:
r = conn.urlopen("GET", url, retries=0)
- self.assertEqual(r.status, 200)
+ assert r.status == 200
except MaxRetryError:
self.fail("Invalid IPv6 format in HTTP CONNECT request")
@@ -1179,9 +1173,9 @@ class TestSSL(SocketDummyServerTestCase):
pool = HTTPSConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
- with self.assertRaises(MaxRetryError) as cm:
+ with pytest.raises(MaxRetryError) as cm:
pool.request("GET", "/", retries=0)
- self.assertIsInstance(cm.exception.reason, SSLError)
+ assert isinstance(cm.value.reason, SSLError)
def test_ssl_read_timeout(self):
timed_out = Event()
@@ -1226,7 +1220,8 @@ class TestSSL(SocketDummyServerTestCase):
timeout=Timeout(connect=1, read=0.01),
)
try:
- self.assertRaises(ReadTimeoutError, response.read)
+ with pytest.raises(ReadTimeoutError):
+ response.read()
finally:
timed_out.set()
@@ -1272,11 +1267,12 @@ class TestSSL(SocketDummyServerTestCase):
finally:
pool.close()
- with self.assertRaises(MaxRetryError) as cm:
+ with pytest.raises(MaxRetryError) as cm:
request()
- self.assertIsInstance(cm.exception.reason, SSLError)
+ assert isinstance(cm.value.reason, SSLError)
# Should not hang, see https://github.com/shazow/urllib3/issues/529
- self.assertRaises(MaxRetryError, request)
+ with pytest.raises(MaxRetryError):
+ request()
def test_retry_ssl_error(self):
def socket_handler(listener):
@@ -1330,7 +1326,7 @@ class TestSSL(SocketDummyServerTestCase):
pool = HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA)
self.addCleanup(pool.close)
response = pool.urlopen("GET", "/", retries=1)
- self.assertEqual(response.data, b"Success")
+ assert response.data == b"Success"
def test_ssl_load_default_certs_when_empty(self):
def socket_handler(listener):
@@ -1367,7 +1363,7 @@ class TestSSL(SocketDummyServerTestCase):
pool = HTTPSConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
- with self.assertRaises(MaxRetryError):
+ with pytest.raises(MaxRetryError):
pool.request("GET", "/", timeout=0.01)
context.load_default_certs.assert_called_with()
@@ -1414,7 +1410,7 @@ class TestSSL(SocketDummyServerTestCase):
pool = HTTPSConnectionPool(self.host, self.port, **kwargs)
self.addCleanup(pool.close)
- with self.assertRaises(MaxRetryError):
+ with pytest.raises(MaxRetryError):
pool.request("GET", "/", timeout=0.01)
context.load_default_certs.assert_not_called()
@@ -1427,7 +1423,8 @@ class TestErrorWrapping(SocketDummyServerTestCase):
)
pool = HTTPConnectionPool(self.host, self.port, retries=False)
self.addCleanup(pool.close)
- self.assertRaises(ProtocolError, pool.request, "GET", "/")
+ with pytest.raises(ProtocolError):
+ pool.request("GET", "/")
def test_unknown_protocol(self):
self.start_response_handler(
@@ -1435,7 +1432,8 @@ class TestErrorWrapping(SocketDummyServerTestCase):
)
pool = HTTPConnectionPool(self.host, self.port, retries=False)
self.addCleanup(pool.close)
- self.assertRaises(ProtocolError, pool.request, "GET", "/")
+ with pytest.raises(ProtocolError):
+ pool.request("GET", "/")
class TestHeaders(SocketDummyServerTestCase):
@@ -1451,9 +1449,7 @@ class TestHeaders(SocketDummyServerTestCase):
self.addCleanup(pool.close)
HEADERS = {"Content-Length": "0", "Content-type": "text/plain"}
r = pool.request("GET", "/")
- self.assertEqual(
- HEADERS, dict(r.headers.items())
- ) # to preserve case sensitivity
+ assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity
def test_headers_are_sent_with_the_original_case(self):
headers = {"foo": "bar", "bAz": "quux"}
@@ -1490,7 +1486,7 @@ class TestHeaders(SocketDummyServerTestCase):
pool = HTTPConnectionPool(self.host, self.port, retries=False)
self.addCleanup(pool.close)
pool.request("GET", "/", headers=HTTPHeaderDict(headers))
- self.assertEqual(expected_headers, parsed_headers)
+ assert expected_headers == parsed_headers
def test_request_headers_are_sent_in_the_original_order(self):
# NOTE: Probability this test gives a false negative is 1/(K!)
@@ -1534,7 +1530,7 @@ class TestHeaders(SocketDummyServerTestCase):
pool = HTTPConnectionPool(self.host, self.port, retries=False)
self.addCleanup(pool.close)
pool.request("GET", "/", headers=OrderedDict(expected_request_headers))
- self.assertEqual(expected_request_headers, actual_request_headers)
+ assert expected_request_headers == actual_request_headers
@fails_on_travis_gce
def test_request_host_header_ignores_fqdn_dot(self):
@@ -1605,7 +1601,7 @@ class TestHeaders(SocketDummyServerTestCase):
actual_response_headers = [
(k, v) for (k, v) in r.headers.items() if k.startswith("X-Header-")
]
- self.assertEqual(expected_response_headers, actual_response_headers)
+ assert expected_response_headers == actual_response_headers
@pytest.mark.skipif(
@@ -1689,7 +1685,7 @@ class TestHEAD(SocketDummyServerTestCase):
r = pool.request("HEAD", "/", timeout=1, preload_content=False)
# stream will use the read_chunked method here.
- self.assertEqual([], list(r.stream()))
+ assert [] == list(r.stream())
def test_empty_head_response_does_not_hang(self):
self.start_response_handler(
@@ -1703,7 +1699,7 @@ class TestHEAD(SocketDummyServerTestCase):
r = pool.request("HEAD", "/", timeout=1, preload_content=False)
# stream will use the read method here.
- self.assertEqual([], list(r.stream()))
+ assert [] == list(r.stream())
class TestStream(SocketDummyServerTestCase):
@@ -1733,7 +1729,7 @@ class TestStream(SocketDummyServerTestCase):
r = pool.request("GET", "/", timeout=1, preload_content=False)
# Stream should read to the end.
- self.assertEqual([b"hello, world"], list(r.stream(None)))
+ assert [b"hello, world"] == list(r.stream(None))
done_event.set()
@@ -1773,9 +1769,9 @@ class TestBadContentLength(SocketDummyServerTestCase):
next(data)
try:
next(data)
- self.assertFail()
+ assert False
except ProtocolError as e:
- self.assertIn("12 bytes read, 10 more expected", str(e))
+ assert "12 bytes read, 10 more expected" in str(e)
done_event.set()
@@ -1807,7 +1803,7 @@ class TestBadContentLength(SocketDummyServerTestCase):
"HEAD", url="/", preload_content=False, enforce_content_length=True
)
data = [chunk for chunk in head_response.stream(1)]
- self.assertEqual(len(data), 0)
+ assert len(data) == 0
done_event.set()