@@ -545,6 +545,51 @@ def test_dict_popstring(self):
545545 # CRASHES dict_popstring({}, NULL)
546546 # CRASHES dict_popstring({"a": 1}, NULL)
547547
548+ def test_dict_fromitems (self ):
549+ # Test PyDict_FromItems()
550+ dict_fromitems = _testcapi .dict_fromitems
551+
552+ d = dict_fromitems ((), 1 , (), 1 )
553+ self .assertEqual (d , {})
554+
555+ d = dict_fromitems (tuple (range (1 , 4 )), 1 , tuple ('abc' ), 1 )
556+ self .assertEqual (d , {1 : 'a' , 2 : 'b' , 3 : 'c' })
557+
558+ # test unicode keys
559+ d = dict_fromitems (tuple ('abc' ), 1 , tuple (range (1 , 4 )), 1 )
560+ self .assertEqual (d , {'a' : 1 , 'b' : 2 , 'c' : 3 })
561+
562+ # test "large" dict (1024 items)
563+ d = dict_fromitems (tuple (range (1024 )), 1 ,
564+ tuple (map (str , range (1024 ))), 1 )
565+ self .assertEqual (d , {i : str (i ) for i in range (1024 )})
566+
567+ # same array for keys and values with keys_offset=values_offset=2
568+ array = ('a' , 1 , 'b' , 2 , 'c' , 3 )
569+ d = dict_fromitems (array , 2 )
570+ self .assertEqual (d , {'a' : 1 , 'b' : 2 , 'c' : 3 })
571+
572+ array = ('a' , 1 , None , 'b' , 2 , None , 'c' , 3 , None )
573+ d = dict_fromitems (array , 3 )
574+ self .assertEqual (d , {'a' : 1 , 'b' : 2 , 'c' : 3 })
575+
576+ # Test PyDict_FromItems(NULL, 0, NULL, 0, 0)
577+ d = dict_fromitems ()
578+ self .assertEqual (d , {})
579+
580+ # test invalid arguments
581+ errmsg = "keys_offset must be greater than 0"
582+ with self .assertRaisesRegex (ValueError , errmsg ):
583+ dict_fromitems (tuple ('abc' ), 0 , tuple (range (1 , 4 )), 1 )
584+
585+ errmsg = "values_offset must be greater than 0"
586+ with self .assertRaisesRegex (ValueError , errmsg ):
587+ dict_fromitems (tuple ('abc' ), 1 , tuple (range (1 , 4 )), 0 )
588+
589+ errmsg = "length must be greater than or equal to 0"
590+ with self .assertRaisesRegex (ValueError , errmsg ):
591+ dict_fromitems (tuple ('abc' ), 1 , tuple (range (1 , 4 )), 1 , - 1 )
592+
548593
549594if __name__ == "__main__" :
550595 unittest .main ()
0 commit comments