Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 21 additions & 13 deletions Lib/ipaddress.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,12 @@ def _prefix_from_ip_int(cls, ip_int):
return prefixlen

@classmethod
def _report_invalid_netmask(cls, netmask_str):
def _report_invalid_netmask(cls, netmask_str, suppress=True):
msg = '%r is not a valid netmask' % netmask_str
raise NetmaskValueError(msg) from None
if suppress:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In some cases there is no other exception to suppress. When we call this function not from the except block.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can check whether sys.exception() is None.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though, do you need to? What's the harm in "from None" when you are not in an except block?

raise NetmaskValueError(msg) from None
else:
raise NetmaskValueError(msg)

@classmethod
def _prefix_from_prefix_string(cls, prefixlen_str):
Expand All @@ -489,13 +492,13 @@ def _prefix_from_prefix_string(cls, prefixlen_str):
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
cls._report_invalid_netmask(prefixlen_str)
cls._report_invalid_netmask(prefixlen_str, suppress=False)
try:
prefixlen = int(prefixlen_str)
except ValueError:
cls._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen_str)
cls._report_invalid_netmask(prefixlen_str, suppress=False)
return prefixlen

@classmethod
Expand Down Expand Up @@ -1160,19 +1163,24 @@ def _make_netmask(cls, arg):
if isinstance(arg, int):
prefixlen = arg
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen)
cls._report_invalid_netmask(prefixlen, suppress=False)
else:
try:
# Check for a netmask in prefix length form
prefixlen = cls._prefix_from_prefix_string(arg)
except NetmaskValueError:
# Check for a netmask or hostmask in dotted-quad form.
# This may raise NetmaskValueError.
prefixlen = cls._prefix_from_ip_string(arg)
prefixlen = cls._prefix_from_string(arg)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was moved to a separate function because it is hard to write it correctly without return. Otherwise we would need to write something like (not tested):

        try:
            prefixlen = cls._prefix_from_prefix_string(arg)
        except NetmaskValueError:
            try:
                prefixlen = cls._prefix_from_ip_string(arg)
            except BaseException as exc:
                raise exc from None
netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
cls._netmask_cache[arg] = netmask, prefixlen
return cls._netmask_cache[arg]

@classmethod
def _prefix_from_string(cls, arg):
try:
# Check for a netmask in prefix length form
return cls._prefix_from_prefix_string(arg)
except NetmaskValueError:
pass
# Check for a netmask or hostmask in dotted-quad form.
# This may raise NetmaskValueError.
return cls._prefix_from_ip_string(arg)

@classmethod
def _ip_int_from_string(cls, ip_str):
"""Turn the given IP string into an integer for comparison.
Expand Down Expand Up @@ -1592,7 +1600,7 @@ def _make_netmask(cls, arg):
if isinstance(arg, int):
prefixlen = arg
if not (0 <= prefixlen <= cls._max_prefixlen):
cls._report_invalid_netmask(prefixlen)
cls._report_invalid_netmask(prefixlen, suppress=False)
else:
prefixlen = cls._prefix_from_prefix_string(arg)
netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
Expand Down
10 changes: 5 additions & 5 deletions Lib/test/test_configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1893,7 +1893,7 @@ def test_get_basic_interpolation(self):
cm = self.assertRaises(configparser.InterpolationMissingOptionError)
with cm:
parser.get('Paths', 'my_dir')
self.assertIs(cm.exception.__suppress_context__, True)
self.assertIsNone(cm.exception.__context__)

def test_get_extended_interpolation(self):
parser = configparser.ConfigParser(
Expand All @@ -1907,7 +1907,7 @@ def test_get_extended_interpolation(self):
cm = self.assertRaises(configparser.InterpolationMissingOptionError)
with cm:
parser.get('Paths', 'my_dir')
self.assertIs(cm.exception.__suppress_context__, True)
self.assertIsNone(cm.exception.__context__)

def test_missing_options(self):
parser = configparser.ConfigParser()
Expand All @@ -1917,19 +1917,19 @@ def test_missing_options(self):
""")
with self.assertRaises(configparser.NoSectionError) as cm:
parser.options('test')
self.assertIs(cm.exception.__suppress_context__, True)
self.assertIsNone(cm.exception.__context__)

def test_missing_section(self):
config = configparser.ConfigParser()
with self.assertRaises(configparser.NoSectionError) as cm:
config.set('Section1', 'an_int', '15')
self.assertIs(cm.exception.__suppress_context__, True)
self.assertIsNone(cm.exception.__context__)

def test_remove_option(self):
config = configparser.ConfigParser()
with self.assertRaises(configparser.NoSectionError) as cm:
config.remove_option('Section1', 'an_int')
self.assertIs(cm.exception.__suppress_context__, True)
self.assertIsNone(cm.exception.__context__)


class ConvertersTestCase(BasicTestCase, unittest.TestCase):
Expand Down
8 changes: 4 additions & 4 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -920,10 +920,10 @@ def first():

exc = err_ctx.exception
self.assertIsInstance(exc, UniqueException)
self.assertIsInstance(exc.__context__, UniqueRuntimeError)
self.assertIsNone(exc.__context__.__context__)
self.assertIsNone(exc.__context__.__cause__)
self.assertIs(exc.__cause__, exc.__context__)
self.assertIsInstance(exc.__cause__, UniqueRuntimeError)
self.assertIsNone(exc.__cause__.__context__)
self.assertIsNone(exc.__cause__.__cause__)
self.assertIsNone(exc.__context__)


class TestExitStack(TestBaseExitStack, unittest.TestCase):
Expand Down
4 changes: 3 additions & 1 deletion Lib/test/test_ipaddress.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ def assertCleanError(self, exc_type, details, *args):
yield exc
# Ensure we produce clean tracebacks on failure
if exc.exception.__context__ is not None:
self.assertTrue(exc.exception.__suppress_context__)
self.assertFalse(exc.exception.__suppress_context__)
self.assertIsNone(exc.exception.__context__)
self.assertIsNone(exc.exception.__cause__)

def assertAddressError(self, details, *args):
"""Ensure a clean AddressValueError"""
Expand Down
15 changes: 11 additions & 4 deletions Lib/test/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -995,12 +995,19 @@ def test_key_type(self):
with self.assertRaises(KeyError) as cm:
os.environ[missing]
self.assertIs(cm.exception.args[0], missing)
self.assertTrue(cm.exception.__suppress_context__)
self.assertFalse(cm.exception.__suppress_context__)
self.assertIsNone(cm.exception.__context__)
self.assertIsNone(cm.exception.__cause__)

with self.assertRaises(KeyError) as cm:
del os.environ[missing]
try:
1/0
except:
with self.assertRaises(KeyError) as cm:
del os.environ[missing]
self.assertIs(cm.exception.args[0], missing)
self.assertTrue(cm.exception.__suppress_context__)
self.assertFalse(cm.exception.__suppress_context__)
self.assertIsInstance(cm.exception.__context__, ZeroDivisionError)
self.assertIsNone(cm.exception.__cause__)

def _test_environ_iteration(self, collection):
iterator = iter(collection)
Expand Down
130 changes: 125 additions & 5 deletions Lib/test/test_raise.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,24 @@ def reraise():
nested_reraise()
self.assertRaises(TypeError, reraise)

def test_raise_from_None(self):
def test_raise_from_None1(self):
try:
raise TypeError("foo")
except:
try:
raise ValueError() from None
except ValueError as e:
self.assertIsInstance(e.__context__, TypeError)
self.assertIsNone(e.__cause__)

def test_raise_from_None2(self):
try:
try:
raise TypeError("foo")
except:
raise ValueError() from None
except ValueError as e:
self.assertIsInstance(e.__context__, TypeError)
self.assertIsNone(e.__context__)
self.assertIsNone(e.__cause__)

def test_with_reraise1(self):
Expand Down Expand Up @@ -150,7 +160,27 @@ def test_assert_with_tuple_arg(self):

class TestCause(unittest.TestCase):

def testCauseSyntax(self):
def testCauseSyntax1(self):
try:
try:
raise TypeError
except Exception:
try:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertIsInstance(exc.__context__, TypeError)
self.assertTrue(exc.__suppress_context__)
exc.__suppress_context__ = False
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsInstance(e.__context__, TypeError)

def testCauseSyntax2(self):
try:
try:
try:
Expand All @@ -159,16 +189,106 @@ def testCauseSyntax(self):
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertTrue(exc.__suppress_context__)
exc.__suppress_context__ = False
self.assertIsNone(exc.__context__)
self.assertFalse(exc.__suppress_context__)
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsNone(e.__context__)

def testCauseSyntax3(self):
try:
try:
1/0
except:
try:
raise TypeError
except Exception:
try:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertIsInstance(exc.__context__, TypeError)
self.assertTrue(exc.__suppress_context__)
exc.__suppress_context__ = False
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsInstance(e.__context__, TypeError)

def testCauseSyntax4(self):
try:
try:
try:
1/0
except:
try:
raise TypeError
except Exception:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertIsInstance(exc.__context__, ZeroDivisionError)
self.assertFalse(exc.__suppress_context__)
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsInstance(e.__context__, ZeroDivisionError)

def testCauseSyntax5(self):
try:
try:
1/0
except:
try:
raise TypeError
except Exception:
try:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertIsInstance(exc.__context__, TypeError)
self.assertTrue(exc.__suppress_context__)
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsInstance(e.__context__, ZeroDivisionError)

def testCauseSyntax6(self):
try:
try:
1/0
except:
try:
try:
raise TypeError
except Exception:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
self.assertIsInstance(exc.__context__, ZeroDivisionError)
self.assertFalse(exc.__suppress_context__)
exc.__suppress_context__ = True
raise exc
except ValueError as exc:
e = exc

self.assertIsNone(e.__cause__)
self.assertFalse(e.__suppress_context__)
self.assertIsNone(e.__context__)

def test_invalid_cause(self):
try:
raise IndexError from 5
Expand Down
22 changes: 16 additions & 6 deletions Lib/test/test_strptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,23 @@ def test_ValueError(self):

def test_strptime_exception_context(self):
# check that this doesn't chain exceptions needlessly (see #17572)
with self.assertRaises(ValueError) as e:
_strptime._strptime_time('', '%D')
self.assertIs(e.exception.__suppress_context__, True)
try:
1/0
except:
with self.assertRaises(ValueError) as e:
_strptime._strptime_time('', '%D')
self.assertFalse(e.exception.__suppress_context__)
self.assertIsInstance(e.exception.__context__, ZeroDivisionError)
self.assertIsNone(e.exception.__cause__)
# additional check for IndexError branch (issue #19545)
with self.assertRaises(ValueError) as e:
_strptime._strptime_time('19', '%Y %')
self.assertIs(e.exception.__suppress_context__, True)
try:
1/0
except:
with self.assertRaises(ValueError) as e:
_strptime._strptime_time('19', '%Y %')
self.assertFalse(e.exception.__suppress_context__)
self.assertIsInstance(e.exception.__context__, ZeroDivisionError)
self.assertIsNone(e.exception.__cause__)

def test_unconverteddata(self):
# Check ValueError is raised when there is unconverted data
Expand Down
8 changes: 6 additions & 2 deletions Lib/test/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,15 @@ def test_strptime_exception_context(self):
# check that this doesn't chain exceptions needlessly (see #17572)
with self.assertRaises(ValueError) as e:
time.strptime('', '%D')
self.assertIs(e.exception.__suppress_context__, True)
self.assertFalse(e.exception.__suppress_context__)
self.assertIsNone(e.exception.__context__)
self.assertIsNone(e.exception.__cause__)
# additional check for IndexError branch (issue #19545)
with self.assertRaises(ValueError) as e:
time.strptime('19', '%Y %')
self.assertIs(e.exception.__suppress_context__, True)
self.assertFalse(e.exception.__suppress_context__)
self.assertIsNone(e.exception.__context__)
self.assertIsNone(e.exception.__cause__)

def test_asctime(self):
time.asctime(time.gmtime(self.t))
Expand Down
Loading