|
6 | 6 | import operator |
7 | 7 | import contextlib |
8 | 8 | import copy |
| 9 | +import time |
9 | 10 |
|
10 | 11 | from test import support |
11 | 12 | from test.support import script_helper |
@@ -72,6 +73,29 @@ def callback(self, ref): |
72 | 73 | self.cbcalled += 1 |
73 | 74 |
|
74 | 75 |
|
| 76 | +@contextlib.contextmanager |
| 77 | +def collect_in_thread(period=0.0001): |
| 78 | + """ |
| 79 | + Ensure GC collections happen in a different thread, at a high frequency. |
| 80 | + """ |
| 81 | + threading = support.import_module('threading') |
| 82 | + please_stop = False |
| 83 | + |
| 84 | + def collect(): |
| 85 | + while not please_stop: |
| 86 | + time.sleep(period) |
| 87 | + gc.collect() |
| 88 | + |
| 89 | + with support.disable_gc(): |
| 90 | + t = threading.Thread(target=collect) |
| 91 | + t.start() |
| 92 | + try: |
| 93 | + yield |
| 94 | + finally: |
| 95 | + please_stop = True |
| 96 | + t.join() |
| 97 | + |
| 98 | + |
75 | 99 | class ReferencesTestCase(TestBase): |
76 | 100 |
|
77 | 101 | def test_basic_ref(self): |
@@ -1633,6 +1657,23 @@ def test_make_weak_keyed_dict_repr(self): |
1633 | 1657 | dict = weakref.WeakKeyDictionary() |
1634 | 1658 | self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>') |
1635 | 1659 |
|
| 1660 | + def test_threaded_weak_valued_setdefault(self): |
| 1661 | + d = weakref.WeakValueDictionary() |
| 1662 | + with collect_in_thread(): |
| 1663 | + for i in range(100000): |
| 1664 | + x = d.setdefault(10, RefCycle()) |
| 1665 | + self.assertIsNot(x, None) # we never put None in there! |
| 1666 | + del x |
| 1667 | + |
| 1668 | + def test_threaded_weak_valued_pop(self): |
| 1669 | + d = weakref.WeakValueDictionary() |
| 1670 | + with collect_in_thread(): |
| 1671 | + for i in range(100000): |
| 1672 | + d[10] = RefCycle() |
| 1673 | + x = d.pop(10, 10) |
| 1674 | + self.assertIsNot(x, None) # we never put None in there! |
| 1675 | + |
| 1676 | + |
1636 | 1677 | from test import mapping_tests |
1637 | 1678 |
|
1638 | 1679 | class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol): |
|
0 commit comments