Prefer pytest.raises over Testcase.fail
It reuses a standard mechanism, is less verbose and avoids including
code that is never executed.
MODIFY
test/contrib/test_socks.py
test/contrib/test_socks.py
@@ -440,12 +440,9 @@ class TestSocks5Proxy(IPV4SocketDummyServerTestCase):
with socks.SOCKSProxyManager(
proxy_url, username="user", password="badpass"
) as pm:
- try:
+ with pytest.raises(NewConnectionError) as e:
pm.request("GET", "http://example.com", retries=False)
- except NewConnectionError as e:
- assert "SOCKS5 authentication failed" in str(e)
- else:
- self.fail("Did not raise")
+ assert "SOCKS5 authentication failed" in str(e.value)
def test_source_address_works(self):
expected_port = _get_free_port(self.host)
@@ -655,12 +652,9 @@ class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase):
self._start_server(request_handler)
proxy_url = "socks4a://%s:%s" % (self.host, self.port)
with socks.SOCKSProxyManager(proxy_url, username="baduser") as pm:
- try:
+ with pytest.raises(NewConnectionError) as e:
pm.request("GET", "http://example.com", retries=False)
- except NewConnectionError as e:
- assert "different user-ids" in str(e)
- else:
- self.fail("Did not raise")
+ assert "different user-ids" in str(e.value)
class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase):

MODIFY
test/with_dummyserver/test_connectionpool.py
test/with_dummyserver/test_connectionpool.py
@@ -75,9 +75,8 @@ class TestConnectionPoolTimeouts(SocketDummyServerTestCase):
conn = pool._get_conn()
pool._put_conn(conn)
try:
+ with pytest.raises(ReadTimeoutError):
pool.urlopen("GET", "/")
- self.fail("The request should fail with a timeout error.")
- except ReadTimeoutError:
if conn.sock:
with pytest.raises(socket.error):
conn.sock.recv(1024)
@@ -385,11 +384,9 @@ class TestConnectionPool(HTTPDummyServerTestCase):
""" ECONNREFUSED error should raise a connection error, with retries """
port = find_unused_port()
with HTTPConnectionPool(self.host, port) as pool:
- try:
+ with pytest.raises(MaxRetryError) as e:
pool.request("GET", "/", retries=Retry(connect=3))
- self.fail("Should have failed with a connection error.")
- except MaxRetryError as e:
- assert type(e.reason) == NewConnectionError
+ assert type(e.value.reason) == NewConnectionError
def test_timeout_success(self):
timeout = Timeout(connect=3, read=5, total=None)
@@ -441,11 +438,9 @@ class TestConnectionPool(HTTPDummyServerTestCase):
def test_bad_connect(self):
with HTTPConnectionPool("badhost.invalid", self.port) as pool:
- try:
+ with pytest.raises(MaxRetryError) as e:
pool.request("GET", "/", retries=5)
- self.fail("should raise timeout exception here")
- except MaxRetryError as e:
- assert type(e.reason) == NewConnectionError
+ assert type(e.value.reason) == NewConnectionError
def test_keepalive(self):
with HTTPConnectionPool(self.host, self.port, block=True, maxsize=1) as pool:
@@ -823,13 +818,8 @@ class TestConnectionPool(HTTPDummyServerTestCase):
class TestRetry(HTTPDummyServerTestCase):
def test_max_retry(self):
with HTTPConnectionPool(self.host, self.port) as pool:
- try:
- r = pool.request("GET", "/redirect", fields={"target": "/"}, retries=0)
- self.fail(
- "Failed to raise MaxRetryError exception, returned %r" % r.status
- )
- except MaxRetryError:
- pass
+ with pytest.raises(MaxRetryError):
+ pool.request("GET", "/redirect", fields={"target": "/"}, retries=0)
def test_disabled_retry(self):
""" Disabled retries should disable redirect handling. """
@@ -1133,11 +1123,9 @@ class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase):
# which is unsupported by BytesIO.
headers = {"Content-Length": "8"}
with HTTPConnectionPool(self.host, self.port, timeout=0.1) as pool:
- try:
+ with pytest.raises(UnrewindableBodyError) as e:
pool.urlopen("PUT", url, headers=headers, body=body)
- self.fail("PUT successful despite failed rewind.")
- except UnrewindableBodyError as e:
- assert "Unable to record file position for" in str(e)
+ assert "Unable to record file position for" in str(e.value)
class TestRetryPoolSize(HTTPDummyServerTestCase):

MODIFY
test/with_dummyserver/test_https.py
test/with_dummyserver/test_https.py
@@ -291,26 +291,22 @@ class TestHTTPS(HTTPSDummyServerTestCase):
with HTTPSConnectionPool(
"127.0.0.1", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA
) as https_pool:
- try:
+ with pytest.raises(MaxRetryError) as e:
https_pool.request("GET", "/")
- self.fail("Didn't raise SSL invalid common name")
- except MaxRetryError as e:
- assert isinstance(e.reason, SSLError)
+ assert isinstance(e.value.reason, SSLError)
assert "doesn't match" in str(
- e.reason
- ) or "certificate verify failed" in str(e.reason)
+ e.value.reason
+ ) or "certificate verify failed" in str(e.value.reason)
def test_verified_with_bad_ca_certs(self):
with HTTPSConnectionPool(
self.host, self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA_BAD
) as https_pool:
- try:
+ with pytest.raises(MaxRetryError) as e:
https_pool.request("GET", "/")
- self.fail("Didn't raise SSL error with bad CA certs")
- except MaxRetryError as e:
- assert isinstance(e.reason, SSLError)
- assert "certificate verify failed" in str(e.reason), (
- "Expected 'certificate verify failed', instead got: %r" % e.reason
+ assert isinstance(e.value.reason, SSLError)
+ assert "certificate verify failed" in str(e.value.reason), (
+ "Expected 'certificate verify failed', instead got: %r" % e.value.reason
)
def test_verified_without_ca_certs(self):
@@ -318,26 +314,21 @@ class TestHTTPS(HTTPSDummyServerTestCase):
with HTTPSConnectionPool(
self.host, self.port, cert_reqs="CERT_REQUIRED"
) as https_pool:
- try:
+ with pytest.raises(MaxRetryError) as e:
https_pool.request("GET", "/")
- self.fail(
- "Didn't raise SSL error with no CA certs when"
- "CERT_REQUIRED is set"
- )
- except MaxRetryError as e:
- assert isinstance(e.reason, SSLError)
+ assert isinstance(e.value.reason, SSLError)
# there is a different error message depending on whether or
# not pyopenssl is injected
assert (
- "No root certificates specified" in str(e.reason)
+ "No root certificates specified" in str(e.value.reason)
# PyPy sometimes uses all-caps here
- or "certificate verify failed" in str(e.reason).lower()
- or "invalid certificate chain" in str(e.reason)
+ or "certificate verify failed" in str(e.value.reason).lower()
+ or "invalid certificate chain" in str(e.value.reason)
), (
"Expected 'No root certificates specified', "
"'certificate verify failed', or "
"'invalid certificate chain', "
- "instead got: %r" % e.reason
+ "instead got: %r" % e.value.reason
)
def test_no_ssl(self):

MODIFY
test/with_dummyserver/test_poolmanager.py
test/with_dummyserver/test_poolmanager.py
@@ -83,7 +83,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
def test_cross_host_redirect(self):
with PoolManager() as http:
cross_host_location = "%s/echo?a=b" % self.base_url_alt
- try:
+ with pytest.raises(MaxRetryError):
http.request(
"GET",
"%s/redirect" % self.base_url,
@@ -91,12 +91,6 @@ class TestPoolManager(HTTPDummyServerTestCase):
timeout=1,
retries=0,
)
- self.fail(
- "Request succeeded instead of raising an exception like it should."
- )
-
- except MaxRetryError:
- pass
r = http.request(
"GET",
@@ -110,8 +104,8 @@ class TestPoolManager(HTTPDummyServerTestCase):
def test_too_many_redirects(self):
with PoolManager() as http:
- try:
- r = http.request(
+ with pytest.raises(MaxRetryError):
+ http.request(
"GET",
"%s/redirect" % self.base_url,
fields={
@@ -120,14 +114,9 @@ class TestPoolManager(HTTPDummyServerTestCase):
},
retries=1,
)
- self.fail(
- "Failed to raise MaxRetryError exception, returned %r" % r.status
- )
- except MaxRetryError:
- pass
- try:
- r = http.request(
+ with pytest.raises(MaxRetryError):
+ http.request(
"GET",
"%s/redirect" % self.base_url,
fields={
@@ -136,11 +125,6 @@ class TestPoolManager(HTTPDummyServerTestCase):
},
retries=Retry(total=None, redirect=1),
)
- self.fail(
- "Failed to raise MaxRetryError exception, returned %r" % r.status
- )
- except MaxRetryError:
- pass
def test_redirect_cross_host_remove_headers(self):
with PoolManager() as http:
@@ -235,7 +219,7 @@ class TestPoolManager(HTTPDummyServerTestCase):
def test_raise_on_status(self):
with PoolManager() as http:
- try:
+ with pytest.raises(MaxRetryError):
# the default is to raise
r = http.request(
"GET",
@@ -243,13 +227,8 @@ class TestPoolManager(HTTPDummyServerTestCase):
fields={"status": "500 Internal Server Error"},
retries=Retry(total=1, status_forcelist=range(500, 600)),
)
- self.fail(
- "Failed to raise MaxRetryError exception, returned %r" % r.status
- )
- except MaxRetryError:
- pass
- try:
+ with pytest.raises(MaxRetryError):
# raise explicitly
r = http.request(
"GET",
@@ -259,11 +238,6 @@ class TestPoolManager(HTTPDummyServerTestCase):
total=1, status_forcelist=range(500, 600), raise_on_status=True
),
)
- self.fail(
- "Failed to raise MaxRetryError exception, returned %r" % r.status
- )
- except MaxRetryError:
- pass
# don't raise
r = http.request(

MODIFY
test/with_dummyserver/test_proxy_poolmanager.py
test/with_dummyserver/test_proxy_poolmanager.py
@@ -61,11 +61,9 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
with pytest.raises(MaxRetryError):
http.request("GET", "%s/" % self.http_url)
- try:
+ with pytest.raises(MaxRetryError) as e:
http.request("GET", "%s/" % self.http_url)
- self.fail("Failed to raise retry error.")
- except MaxRetryError as e:
- assert type(e.reason) == ProxyError
+ assert type(e.value.reason) == ProxyError
def test_oldapi(self):
with ProxyManager(
@@ -82,13 +80,11 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA_BAD
) as http:
https_pool = http._new_pool("https", self.https_host, self.https_port)
- try:
+ with pytest.raises(MaxRetryError) as e:
https_pool.request("GET", "/", retries=0)
- self.fail("Didn't raise SSL error with wrong CA")
- except MaxRetryError as e:
- assert isinstance(e.reason, SSLError)
- assert "certificate verify failed" in str(e.reason), (
- "Expected 'certificate verify failed', instead got: %r" % e.reason
+ assert isinstance(e.value.reason, SSLError)
+ assert "certificate verify failed" in str(e.value.reason), (
+ "Expected 'certificate verify failed', instead got: %r" % e.value.reason
)
http = proxy_from_url(
@@ -105,12 +101,10 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
)
https_fail_pool = http._new_pool("https", "127.0.0.1", self.https_port)
- try:
+ with pytest.raises(MaxRetryError) as e:
https_fail_pool.request("GET", "/", retries=0)
- self.fail("Didn't raise SSL invalid common name")
- except MaxRetryError as e:
- assert isinstance(e.reason, SSLError)
- assert "doesn't match" in str(e.reason)
+ assert isinstance(e.value.reason, SSLError)
+ assert "doesn't match" in str(e.value.reason)
def test_redirect(self):
with proxy_from_url(self.proxy_url) as http:
@@ -135,7 +129,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
def test_cross_host_redirect(self):
with proxy_from_url(self.proxy_url) as http:
cross_host_location = "%s/echo?a=b" % self.http_url_alt
- try:
+ with pytest.raises(MaxRetryError):
http.request(
"GET",
"%s/redirect" % self.http_url,
@@ -143,10 +137,6 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
timeout=1,
retries=0,
)
- self.fail("We don't want to follow redirects here.")
-
- except MaxRetryError:
- pass
r = http.request(
"GET",
@@ -160,7 +150,7 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
def test_cross_protocol_redirect(self):
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
cross_protocol_location = "%s/echo?a=b" % self.https_url
- try:
+ with pytest.raises(MaxRetryError):
http.request(
"GET",
"%s/redirect" % self.http_url,
@@ -168,10 +158,6 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
timeout=1,
retries=0,
)
- self.fail("We don't want to follow redirects here.")
-
- except MaxRetryError:
- pass
r = http.request(
"GET",
@@ -334,11 +320,9 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
@requires_network
def test_https_proxy_timeout(self):
with proxy_from_url("https://{host}".format(host=TARPIT_HOST)) as https:
- try:
+ with pytest.raises(MaxRetryError) as e:
https.request("GET", self.http_url, timeout=0.001)
- self.fail("Failed to raise retry error.")
- except MaxRetryError as e:
- assert type(e.reason) == ConnectTimeoutError
+ assert type(e.value.reason) == ConnectTimeoutError
@pytest.mark.timeout(0.5)
@requires_network
@@ -346,11 +330,9 @@ class TestHTTPProxyManager(HTTPDummyProxyTestCase):
with proxy_from_url(
"https://{host}".format(host=TARPIT_HOST), timeout=0.001
) as https:
- try:
+ with pytest.raises(MaxRetryError) as e:
https.request("GET", self.http_url)
- self.fail("Failed to raise retry error.")
- except MaxRetryError as e:
- assert type(e.reason) == ConnectTimeoutError
+ assert type(e.value.reason) == ConnectTimeoutError
def test_scheme_host_case_insensitive(self):
"""Assert that upper-case schemes and hosts are normalized."""

MODIFY
test/with_dummyserver/test_socketlevel.py
test/with_dummyserver/test_socketlevel.py
@@ -229,16 +229,10 @@ class TestClientCerts(SocketDummyServerTestCase):
with HTTPSConnectionPool(
self.host, self.port, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA
) as pool:
- try:
+ with pytest.raises(MaxRetryError):
pool.request("GET", "/", retries=0)
- except MaxRetryError:
done_receiving.set()
- else:
done_receiving.set()
- self.fail(
- "Expected server to reject connection due to missing client "
- "certificates"
- )
@requires_ssl_context_keyfile_password
def test_client_cert_with_string_password(self):
@@ -812,8 +806,7 @@ class TestSocketClosing(SocketDummyServerTestCase):
done_closing.set() # wait until the socket in our pool gets closed
successful = complete.wait(timeout=1)
- if not successful:
- self.fail("Timed out waiting for connection close")
+ assert successful, "Timed out waiting for connection close"
def test_release_conn_param_is_respected_after_timeout_retry(self):
"""For successful ```urlopen(release_conn=False)```,

Prefer pytest.raises over Testcase.fail (#1712)

It reuses a standard mechanism, is less verbose and avoids including
code that is never executed.