@@ -407,5 +407,51 @@ def test_none_in_tuples(self):
407407
408408#==============================================================================
409409
410+ class TestKeylist (unittest .TestCase ):
411+ def test_exclusivity_with_key (self ):
412+ msg = 'Only one of key and keylist can be provided.'
413+ with self .assertRaisesRegex (ValueError , msg ):
414+ [].sort (key = 1 , keylist = 1 )
415+
416+ def test_argtype (self ):
417+ msg = 'Only one of key and keylist can be provided.'
418+ for arg in [1 , (), iter (())]:
419+ msg = f"'{ type (arg ).__name__ } ' object is not a list"
420+ with self .assertRaisesRegex (TypeError , msg ):
421+ [].sort (keylist = arg )
422+
423+ def test_unequal_sizes (self ):
424+ msg = 'Lengths of input list and keylist differ.'
425+ for arg in [[1 , 2 ], [1 , 2 , 3 , 4 ]]:
426+ with self .assertRaisesRegex (ValueError , msg ):
427+ [1 , 2 , 3 ].sort (keylist = arg )
428+
429+ def test_keylist_vs_key (self ):
430+ data = list (range (10 ))
431+ # NOTE: BORLAND32
432+ keyfunc = lambda x : ((22695477 * x + 1 ) % 2 ** 32 ) % 10
433+ keylist = list (map (keyfunc , data ))
434+ res_keyfunc = sorted (data , key = keyfunc )
435+ res_keylist = sorted (data , keylist = keylist )
436+ self .assertEqual (res_keyfunc , res_keylist )
437+
438+ def test_mutability_plus (self ):
439+ for size in [10 , 100 , 1000 ]:
440+ data = list (range (size ))
441+ # NOTE: BORLAND32
442+ keyfunc = lambda x : ((22695477 * x + 1 ) % 2 ** 32 ) % size
443+ keylist = list (map (keyfunc , data ))
444+ orig_keylist = list (keylist )
445+
446+ expected_keylist = sorted (keylist )
447+ result = sorted (data , keylist = keylist )
448+ self .assertEqual (keylist , expected_keylist )
449+
450+ # And for completeness check the result
451+ idxs = sorted (range (len (keylist )), key = orig_keylist .__getitem__ )
452+ expected_result = [data [i ] for i in idxs ]
453+ self .assertEqual (result , expected_result )
454+
455+
410456if __name__ == "__main__" :
411457 unittest .main ()
0 commit comments