|
1 | 1 | import sys
|
2 | 2 | import unittest
|
3 |
| -from test import support |
4 | 3 | from test.support import import_helper
|
5 | 4 | from collections import UserList
|
6 | 5 |
|
| 6 | + |
7 | 7 | py_bisect = import_helper.import_fresh_module('bisect', blocked=['_bisect'])
|
8 | 8 | c_bisect = import_helper.import_fresh_module('bisect', fresh=['bisect'])
|
9 | 9 |
|
@@ -200,6 +200,63 @@ def test_keyword_args(self):
|
200 | 200 | self.module.insort(a=data, x=25, lo=1, hi=3)
|
201 | 201 | self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50])
|
202 | 202 |
|
| 203 | + def test_lookups_with_key_function(self): |
| 204 | + mod = self.module |
| 205 | + |
| 206 | + # Invariant: Index with a keyfunc on an array |
| 207 | + # should match the index on an array where |
| 208 | + # key function has already been applied. |
| 209 | + |
| 210 | + keyfunc = abs |
| 211 | + arr = sorted([2, -4, 6, 8, -10], key=keyfunc) |
| 212 | + precomputed_arr = list(map(keyfunc, arr)) |
| 213 | + for x in precomputed_arr: |
| 214 | + self.assertEqual( |
| 215 | + mod.bisect_left(arr, x, key=keyfunc), |
| 216 | + mod.bisect_left(precomputed_arr, x) |
| 217 | + ) |
| 218 | + self.assertEqual( |
| 219 | + mod.bisect_right(arr, x, key=keyfunc), |
| 220 | + mod.bisect_right(precomputed_arr, x) |
| 221 | + ) |
| 222 | + |
| 223 | + keyfunc = str.casefold |
| 224 | + arr = sorted('aBcDeEfgHhiIiij', key=keyfunc) |
| 225 | + precomputed_arr = list(map(keyfunc, arr)) |
| 226 | + for x in precomputed_arr: |
| 227 | + self.assertEqual( |
| 228 | + mod.bisect_left(arr, x, key=keyfunc), |
| 229 | + mod.bisect_left(precomputed_arr, x) |
| 230 | + ) |
| 231 | + self.assertEqual( |
| 232 | + mod.bisect_right(arr, x, key=keyfunc), |
| 233 | + mod.bisect_right(precomputed_arr, x) |
| 234 | + ) |
| 235 | + |
| 236 | + def test_insort(self): |
| 237 | + from random import shuffle |
| 238 | + mod = self.module |
| 239 | + |
| 240 | + # Invariant: As random elements are inserted in |
| 241 | + # a target list, the targetlist remains sorted. |
| 242 | + keyfunc = abs |
| 243 | + data = list(range(-10, 11)) + list(range(-20, 20, 2)) |
| 244 | + shuffle(data) |
| 245 | + target = [] |
| 246 | + for x in data: |
| 247 | + mod.insort_left(target, x, key=keyfunc) |
| 248 | + self.assertEqual( |
| 249 | + sorted(target, key=keyfunc), |
| 250 | + target |
| 251 | + ) |
| 252 | + target = [] |
| 253 | + for x in data: |
| 254 | + mod.insort_right(target, x, key=keyfunc) |
| 255 | + self.assertEqual( |
| 256 | + sorted(target, key=keyfunc), |
| 257 | + target |
| 258 | + ) |
| 259 | + |
203 | 260 | class TestBisectPython(TestBisect, unittest.TestCase):
|
204 | 261 | module = py_bisect
|
205 | 262 |
|
|
0 commit comments