From 3995dac9d118d05f74163a8d714173e34f6ca7a1 Mon Sep 17 00:00:00 2001 From: Wolfgang Maier Date: Sun, 1 Apr 2018 22:07:46 +0200 Subject: [PATCH 1/2] Ensure random.choice always raises IndexError on empty sequence Without this patch a ZeroDivisionError was leaked for Random subclasses overriding the random, but not the getrandbits method. --- Lib/random.py | 2 ++ Lib/test/test_random.py | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Lib/random.py b/Lib/random.py index 91065b7e303784..0bc24174e13f14 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -242,6 +242,8 @@ def _randbelow(self, n, int=int, maxsize=1<= maxsize) self.gen._randbelow(maxsize+1, maxsize = maxsize) self.gen._randbelow(5640, maxsize = maxsize) - + # issue 33203: test that _randbelow raises ValueError on + # n == 0 also in its getrandbits-independent branch. + with self.assertRaises(ValueError): + self.gen._randbelow(0, maxsize=maxsize) # This might be going too far to test a single line, but because of our # noble aim of achieving 100% test coverage we need to write a case in # which the following line in Random._randbelow() gets executed: From 6c6088e60e7987734a4a6b5c08236f34d50fc09c Mon Sep 17 00:00:00 2001 From: Wolfgang Maier Date: Thu, 5 Apr 2018 11:30:47 +0200 Subject: [PATCH 2/2] Add Misc/NEWS.d entry --- .../next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst diff --git a/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst b/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst new file mode 100644 index 00000000000000..ab6d17b5d1baf1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-04-05-11-09-45.bpo-33203.Hje9Py.rst @@ -0,0 +1,3 @@ +``random.Random.choice()`` now raises ``IndexError`` for empty sequences +consistently even when called from subclasses without a ``getrandbits()`` +implementation.