MCPcopy Index your code
hub / github.com/python/cpython / test_sample_with_counts

Method test_sample_with_counts

Lib/test/test_random.py:205–259  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

203 self.gen.sample(population, k=2)
204
205 def test_sample_with_counts(self):
206 sample = self.gen.sample
207
208 # General case
209 colors = ['red', 'green', 'blue', 'orange', 'black', 'brown', 'amber']
210 counts = [500, 200, 20, 10, 5, 0, 1 ]
211 k = 700
212 summary = Counter(sample(colors, counts=counts, k=k))
213 self.assertEqual(sum(summary.values()), k)
214 for color, weight in zip(colors, counts):
215 self.assertLessEqual(summary[color], weight)
216 self.assertNotIn('brown', summary)
217
218 # Case that exhausts the population
219 k = sum(counts)
220 summary = Counter(sample(colors, counts=counts, k=k))
221 self.assertEqual(sum(summary.values()), k)
222 for color, weight in zip(colors, counts):
223 self.assertLessEqual(summary[color], weight)
224 self.assertNotIn('brown', summary)
225
226 # Case with population size of 1
227 summary = Counter(sample(['x'], counts=[10], k=8))
228 self.assertEqual(summary, Counter(x=8))
229
230 # Case with all counts equal.
231 nc = len(colors)
232 summary = Counter(sample(colors, counts=[10]*nc, k=10*nc))
233 self.assertEqual(summary, Counter(10*colors))
234
235 # Test error handling
236 with self.assertRaises(TypeError):
237 sample(['red', 'green', 'blue'], counts=10, k=10) # counts not iterable
238 with self.assertRaises(ValueError):
239 sample(['red', 'green', 'blue'], counts=[-3, -7, -8], k=2) # counts are negative
240 with self.assertRaises(ValueError):
241 sample(['red', 'green'], counts=[10, 10], k=21) # population too small
242 with self.assertRaises(ValueError):
243 sample(['red', 'green', 'blue'], counts=[1, 2], k=2) # too few counts
244 with self.assertRaises(ValueError):
245 sample(['red', 'green', 'blue'], counts=[1, 2, 3, 4], k=2) # too many counts
246
247 # Cases with zero counts match equivalents without counts (see gh-130285)
248 self.assertEqual(
249 sample('abc', k=0, counts=[0, 0, 0]),
250 sample([], k=0),
251 )
252 self.assertEqual(
253 sample([], 0, counts=[]),
254 sample([], 0),
255 )
256 with self.assertRaises(ValueError):
257 sample([], 1, counts=[])
258 with self.assertRaises(ValueError):
259 sample('x', 1, counts=[0])
260
261 def test_choices(self):
262 choices = self.gen.choices

Callers

nothing calls this directly

Calls 7

CounterClass · 0.90
sampleFunction · 0.85
assertLessEqualMethod · 0.80
assertNotInMethod · 0.80
assertEqualMethod · 0.45
valuesMethod · 0.45
assertRaisesMethod · 0.45

Tested by

no test coverage detected