@@ -57,6 +57,9 @@ class IntLike(WithDunder):
5757class FloatLike (WithDunder ):
5858 methname = '__float__'
5959
60+ class ComplexLike (WithDunder ):
61+ methname = '__complex__'
62+
6063
6164def subclassof (base ):
6265 return type (base .__name__ + 'Subclass' , (base ,), {})
@@ -302,6 +305,47 @@ def test_float(self):
302305 self .assertRaises (TypeError , float_ , object ())
303306 self .assertRaises (SystemError , float_ , NULL )
304307
308+ def test_complex (self ):
309+ # Test PyNumber_Complex()
310+ complex_ = _testcapi .number_complex
311+
312+ self .assertEqual (complex_ (1.25 ), 1.25 + 0j )
313+ self .assertEqual (complex_ (123 ), 123 + 0j )
314+ self .assertEqual (complex_ ("1.25" ), 1.25 + 0j )
315+ self .assertEqual (complex_ (1 + 2j ), 1 + 2j )
316+ self .assertEqual (complex_ ("1+2j" ), 1 + 2j )
317+
318+ self .assertEqual (complex_ (FloatLike .with_val (4.25 )), 4.25 + 0j )
319+ self .assertEqual (complex_ (IndexLike .with_val (99 )), 99.0 + 0j )
320+ self .assertEqual (complex_ (IndexLike .with_val (- 1 )), - 1.0 + 0j )
321+ self .assertEqual (complex_ (ComplexLike .with_val (1 + 2j )), 1 + 2j )
322+
323+ self .assertRaises (TypeError , complex_ , FloatLike .with_val (687 ))
324+ x = FloatLike .with_val (subclassof (float )(4.25 ))
325+ with warnings .catch_warnings ():
326+ warnings .simplefilter ("error" , DeprecationWarning )
327+ self .assertRaises (DeprecationWarning , complex_ , x )
328+ with self .assertWarns (DeprecationWarning ):
329+ self .assertEqual (complex_ (x ), 4.25 + 0j )
330+ self .assertRaises (RuntimeError , complex_ ,
331+ FloatLike .with_exc (RuntimeError ))
332+
333+ self .assertRaises (TypeError , complex_ , ComplexLike .with_val (687 ))
334+ x = ComplexLike .with_val (subclassof (complex )(1 + 2j ))
335+ with warnings .catch_warnings ():
336+ warnings .simplefilter ("error" , DeprecationWarning )
337+ self .assertRaises (DeprecationWarning , complex_ , x )
338+ with self .assertWarns (DeprecationWarning ):
339+ self .assertEqual (complex_ (x ), 1 + 2j )
340+ self .assertRaises (RuntimeError , complex_ ,
341+ ComplexLike .with_exc (RuntimeError ))
342+
343+ self .assertRaises (TypeError , complex_ , IndexLike .with_val (1.25 ))
344+ self .assertRaises (OverflowError , complex_ , IndexLike .with_val (2 ** 2000 ))
345+
346+ self .assertRaises (TypeError , complex_ , object ())
347+ self .assertRaises (SystemError , complex_ , NULL )
348+
305349 def test_index (self ):
306350 # Test PyNumber_Index()
307351 index = _testcapi .number_index
0 commit comments