| 1 |
import concurrent.futures |
| 2 |
import unittest |
| 3 |
import inspect |
| 4 |
from threading import Barrier |
| 5 |
from unittest import TestCase |
| 6 |
|
| 7 |
from test.support import threading_helper, Py_GIL_DISABLED |
| 8 |
|
| 9 |
threading_helper.requires_working_threading(module=True) |
| 10 |
|
| 11 |
|
| 12 |
def get_func_annotation(f, b): |
| 13 |
b.wait() |
| 14 |
return inspect.get_annotations(f) |
| 15 |
|
| 16 |
|
| 17 |
def get_func_annotation_dunder(f, b): |
| 18 |
b.wait() |
| 19 |
return f.__annotations__ |
| 20 |
|
| 21 |
|
| 22 |
def set_func_annotation(f, b): |
| 23 |
b.wait() |
| 24 |
f.__annotations__ = {'x': int, 'y': int, 'return': int} |
| 25 |
return f.__annotations__ |
| 26 |
|
| 27 |
|
| 28 |
@unittest.skipUnless(Py_GIL_DISABLED, "Enable only in FT build") |
| 29 |
class TestFTFuncAnnotations(TestCase): |
| 30 |
NUM_THREADS = 4 |
| 31 |
|
| 32 |
def test_concurrent_read(self): |
| 33 |
def f(x: int) -> int: |
| 34 |
return x + 1 |
| 35 |
|
| 36 |
for _ in range(10): |
| 37 |
with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: |
| 38 |
b = Barrier(self.NUM_THREADS) |
| 39 |
futures = {executor.submit(get_func_annotation, f, b): i for i in range(self.NUM_THREADS)} |
| 40 |
for fut in concurrent.futures.as_completed(futures): |
| 41 |
annotate = fut.result() |
| 42 |
self.assertIsNotNone(annotate) |
| 43 |
self.assertEqual(annotate, {'x': int, 'return': int}) |
| 44 |
|
| 45 |
with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: |
| 46 |
b = Barrier(self.NUM_THREADS) |
| 47 |
futures = {executor.submit(get_func_annotation_dunder, f, b): i for i in range(self.NUM_THREADS)} |
| 48 |
for fut in concurrent.futures.as_completed(futures): |
| 49 |
annotate = fut.result() |
| 50 |
self.assertIsNotNone(annotate) |
| 51 |
self.assertEqual(annotate, {'x': int, 'return': int}) |
| 52 |
|
| 53 |
def test_concurrent_write(self): |
| 54 |
def bar(x: int, y: float) -> float: |
| 55 |
return y ** x |
| 56 |
|
| 57 |
for _ in range(10): |
| 58 |
with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: |
| 59 |
b = Barrier(self.NUM_THREADS) |
| 60 |
futures = {executor.submit(set_func_annotation, bar, b): i for i in range(self.NUM_THREADS)} |
| 61 |
for fut in concurrent.futures.as_completed(futures): |
| 62 |
annotate = fut.result() |
| 63 |
self.assertIsNotNone(annotate) |
| 64 |
self.assertEqual(annotate, {'x': int, 'y': int, 'return': int}) |
| 65 |
|
| 66 |
# func_get_annotations returns in-place dict, so bar.__annotations__ should be modified as well |
| 67 |
self.assertEqual(bar.__annotations__, {'x': int, 'y': int, 'return': int}) |