bpo-33203: Ensure random.choice always raises IndexError on empty sequence (GH-6338) (GH-6388)
(cherry picked from commit 091e95e900
)
Co-authored-by: Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de>
This commit is contained in:
parent
29bc6f6347
commit
e25af930a3
|
@ -241,6 +241,8 @@ class Random(_random.Random):
|
|||
"enough bits to choose from a population range this large.\n"
|
||||
"To remove the range limitation, add a getrandbits() method.")
|
||||
return int(random() * n)
|
||||
if n == 0:
|
||||
raise ValueError("Boundary cannot be zero")
|
||||
rem = maxsize % n
|
||||
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
|
||||
r = random()
|
||||
|
|
|
@ -644,7 +644,10 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
|
|||
# Population range too large (n >= 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:
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
``random.Random.choice()`` now raises ``IndexError`` for empty sequences
|
||||
consistently even when called from subclasses without a ``getrandbits()``
|
||||
implementation.
|
Loading…
Reference in New Issue