codekingpro/portable-devtools
115k
1import random
2
3import pytest
4
5from numpy._core._multiarray_tests import identityhash_tester
6
7
8@pytest.mark.parametrize("key_length", [1, 3, 6])
9@pytest.mark.parametrize("length", [1, 16, 2000])
10def test_identity_hashtable(key_length, length):
11 # use a 30 object pool for everything (duplicates will happen)
12 pool = [object() for i in range(20)]
13 keys_vals = []
14 for i in range(length):
15 keys = tuple(random.choices(pool, k=key_length))
16 keys_vals.append((keys, random.choice(pool)))
17
18 dictionary = dict(keys_vals)
19
20 # add a random item at the end:
21 keys_vals.append(random.choice(keys_vals))
22 # the expected one could be different with duplicates:
23 expected = dictionary[keys_vals[-1][0]]
24
25 res = identityhash_tester(key_length, keys_vals, replace=True)
26 assert res is expected
27
28 if length == 1:
29 return
30
31 # add a new item with a key that is already used and a new value, this
32 # should error if replace is False, see gh-26690
33 new_key = (keys_vals[1][0], object())
34 keys_vals[0] = new_key
35 with pytest.raises(RuntimeError):
36 identityhash_tester(key_length, keys_vals)
37 