@@ -354,6 +354,80 @@ def test_pyobject_dump(self):
354354 output = self .pyobject_dump (NULL )
355355 self .assertRegex (output , r'<object at .* is freed>' )
356356
357+ def test_object_clear_managed_dict (self ):
358+ # PyObject_ClearManagedDict
359+ clear = _testcapi .pyobject_clear_managed_dict
360+ ManagedDictType = _testcapi .ManagedDictType
361+
362+ obj = ManagedDictType ()
363+ obj .value = 'first'
364+ # asserting `__dict__` is a must to materialize the value before clean:
365+ self .assertEqual (obj .__dict__ , {'value' : 'first' })
366+ self .assertIs (type (obj .__dict__ ), dict )
367+ clear (obj )
368+ self .assertEqual (obj .__dict__ , {})
369+ self .assertIs (type (obj .__dict__ ), dict )
370+
371+ # big object:
372+ obj = ManagedDictType ()
373+ existing_dict = {f'attr_{ x } ' : x for x in range (100 )}
374+ obj .__dict__ = existing_dict
375+ self .assertIs (obj .__dict__ , existing_dict )
376+ clear (obj )
377+ self .assertEqual (obj .__dict__ , {})
378+ self .assertIs (type (obj .__dict__ ), dict )
379+
380+ # empty dict:
381+ obj = ManagedDictType ()
382+ self .assertEqual (obj .__dict__ , {})
383+ self .assertIs (type (obj .__dict__ ), dict )
384+ clear (obj )
385+ self .assertEqual (obj .__dict__ , {})
386+ self .assertIs (type (obj .__dict__ ), dict )
387+
388+ # double clear:
389+ obj = ManagedDictType ()
390+ obj .value = 'first'
391+ self .assertEqual (obj .__dict__ , {'value' : 'first' })
392+ clear (obj )
393+ clear (obj )
394+ self .assertEqual (obj .__dict__ , {})
395+ self .assertIs (type (obj .__dict__ ), dict )
396+
397+ # unmaterialized:
398+ obj = ManagedDictType ()
399+ obj .value = 'first'
400+ clear (obj )
401+ self .assertEqual (obj .__dict__ , {})
402+ self .assertIs (type (obj .__dict__ ), dict )
403+
404+ # CRASHES: clear(NULL)
405+
406+ @threading_helper .requires_working_threading ()
407+ def test_object_clear_managed_dict_ft_memory_error (self ):
408+ # PyObject_ClearManagedDict, gh-152254
409+ clear = _testcapi .pyobject_clear_managed_dict
410+ ManagedDictType = _testcapi .ManagedDictType
411+
412+ obj = ManagedDictType ()
413+ obj .value = 'first'
414+ self .assertEqual (len (obj .__dict__ ), 1 )
415+
416+ def worker ():
417+ # This needs to be in a separate thread for the crash to happen:
418+ with support .catch_unraisable_exception () as ex :
419+ # `clear` used to crash:
420+ _testcapi .call_with_nomemory (0 , 1 , clear , obj )
421+ self .assertIsNotNone (ex .unraisable )
422+ self .assertIs (ex .unraisable .exc_type , MemoryError )
423+ self .assertIn ('managed dict' , ex .unraisable .err_msg )
424+ self .assertEqual (obj .__dict__ , {})
425+ self .assertIs (type (obj .__dict__ ), dict )
426+
427+ threading_helper .run_concurrently ([worker ])
428+ self .assertEqual (obj .__dict__ , {})
429+ self .assertIs (type (obj .__dict__ ), dict )
430+
357431
358432class RefTracerTest (unittest .TestCase ):
359433 @support .requires_resource ('cpu' )
0 commit comments