File: test_futures.py

package info (click to toggle)
mpi4py 4.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,540 kB
  • sloc: python: 34,465; ansic: 16,475; makefile: 614; sh: 325; cpp: 193; f90: 178
file content (1815 lines) | stat: -rw-r--r-- 58,444 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
import functools
import os
import random
import sys
import threading
import time
import unittest
import warnings
from concurrent.futures._base import (
    CANCELLED,
    CANCELLED_AND_NOTIFIED,
    FINISHED,
    PENDING,
    RUNNING,
)
from pathlib import Path

sys.path.append(
    os.fspath(Path(__file__).resolve().parent.parent.parent / "test")
)
import mpitestutil as testutil

from mpi4py import MPI, futures

SHARED_POOL = futures._core.SharedPool is not None
WORLD_SIZE = MPI.COMM_WORLD.Get_size()


def create_future(state=PENDING, exception=None, result=None):
    f = futures.Future()
    f._state = state
    f._exception = exception
    f._result = result
    return f


PENDING_FUTURE = create_future(state=PENDING)
RUNNING_FUTURE = create_future(state=RUNNING)
CANCELLED_FUTURE = create_future(state=CANCELLED)
CANCELLED_AND_NOTIFIED_FUTURE = create_future(state=CANCELLED_AND_NOTIFIED)
EXCEPTION_FUTURE = create_future(state=FINISHED, exception=OSError())
SUCCESSFUL_FUTURE = create_future(state=FINISHED, result=42)


def mul(x, y):  # noqa: FURB118
    return x * y


def sleep_and_raise(t):
    time.sleep(t)
    raise RuntimeError("this is an exception")


def check_global_var(x):
    return global_var == x  # noqa: F821


def check_run_name(name):
    return __name__ == name


def check_comm_workers():
    comm = futures.get_comm_workers()
    return comm.Get_size()


def sys_flags_get(name):
    return getattr(sys.flags, name)


class ExecutorMixin:
    worker_count = 2

    def setUp(self):
        self.t1 = time.time()
        try:
            self.executor = self.executor_type(max_workers=self.worker_count)
        except NotImplementedError as exc:
            self.skipTest(str(exc))
        self._prime_executor()

    def tearDown(self):
        self.executor.shutdown(wait=True)
        dt = time.time() - self.t1
        self.assertLess(dt, 60, "synchronization issue: test lasted too long")

    def _prime_executor(self):
        # Make sure that the executor is ready to do work before running the
        # tests. This should reduce the probability of timeouts in the tests.
        futures = [
            self.executor.submit(time.sleep, 0)
            for _ in range(self.worker_count)
        ]
        for f in futures:
            f.result()


class ProcessPoolMixin(ExecutorMixin):
    executor_type = futures.MPIPoolExecutor

    if "coverage" in sys.modules:
        executor_type = staticmethod(
            functools.partial(
                executor_type,
                python_args="-m coverage run".split(),
            )
        )


@unittest.skipIf(not SHARED_POOL, "not-shared-pool")
class SharedPoolInitTest(unittest.TestCase):
    executor_type = futures.MPIPoolExecutor

    def test_initializer_0(self):
        executor = self.executor_type(
            initializer=time.sleep,
            initargs=(0,),
        )
        executor.bootup()
        executor.submit(time.sleep, 0).result()
        executor.shutdown()

    def test_initializer_1(self):
        for _ in range(2):
            executor = self.executor_type(
                initializer=sleep_and_raise,
                initargs=(0.2,),
            )
            executor.submit(time.sleep, 0).cancel()
            future = executor.submit(time.sleep, 0)
            with self.assertRaises(futures.BrokenExecutor):
                executor.submit(time.sleep, 0).result()
            with self.assertRaises(futures.BrokenExecutor):
                future.result()
            with self.assertRaises(futures.BrokenExecutor):
                executor.submit(time.sleep, 0)

    def test_initializer_2(self):
        executor = self.executor_type(
            initializer=time.sleep,
            initargs=(0,),
        )
        executor.bootup()
        executor.submit(time.sleep, 0).result()
        executor.shutdown()

    def test_initializer_3(self):
        executor = self.executor_type()
        executor.submit(time.sleep, 0).result()
        executor.shutdown()

    def test_initializer_4(self):
        rnd = random.random

        def test(tid):
            with self.executor_type(
                initializer=time.sleep,
                initargs=(rnd() / 100,),
            ) as executor:
                futures.as_completed([
                    executor.submit(time.sleep, rnd() / 100)
                    for _ in range(executor.num_workers + tid)
                ])

        ts = [threading.Thread(target=test, args=(i,)) for i in range(5)]
        for t in ts:
            t.start()
        for t in ts:
            t.join()


class ProcessPoolInitTest(ProcessPoolMixin, unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def _prime_executor(self):
        pass

    def test_init(self):
        self.executor_type()

    def test_init_args(self):
        self.executor_type(1)

    def test_init_kwargs(self):
        executor = self.executor_type(
            python_exe=sys.executable,
            max_workers=None,
            mpi_info={"soft": "0:1"},
            globals=None,
            main=False,
            path=[],
            wdir=Path.cwd(),
            env={},
            use_pkl5=None,
            backoff=0.001,
        )
        futures = [
            executor.submit(time.sleep, 0) for _ in range(self.worker_count)
        ]
        for f in futures:
            f.result()
        executor.shutdown()

    def test_init_pyargs(self):
        executor_type = futures.MPIPoolExecutor
        executor = executor_type(python_args=["-B", "-Wi"])
        executor.submit(time.sleep, 0).result()
        executor.shutdown()

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_init_sys_flags(self):
        executor_type = futures.MPIPoolExecutor
        sys_flags = [
            ("debug", "-d", True),
            ("optimize", "-O", 1),
            ("optimize", "-OO", 2),
            ("dont_write_bytecode", "-B", True),
            ("dev_mode", "-Xdev", True),
            ("utf8_mode", "-Xutf8", True),
        ]
        if sys.version_info >= (3, 11):
            sys_flags.extend([
                ("safe_path", "-P", True),
            ])
        for name, flag, value in sys_flags:
            if not isinstance(value, bool):
                if isinstance(value, int):
                    value += getattr(sys.flags, name)
            with executor_type(python_args=[flag]) as executor:
                result = executor.submit(sys_flags_get, name).result()
            if isinstance(value, bool):
                result = bool(result)
            self.assertEqual(value, result, f"sys.flags.{name}")

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_init_globals(self):
        executor = self.executor_type(globals={"global_var": 42})
        future1 = executor.submit(check_global_var, 42)
        future2 = executor.submit(check_global_var, 24)
        self.assertTrue(future1.result())
        self.assertFalse(future2.result())
        executor.shutdown()

    @unittest.skipIf(SHARED_POOL and WORLD_SIZE == 1, "shared-pool")
    def test_run_name(self):
        executor = self.executor_type()
        run_name = futures._core.MAIN_RUN_NAME
        future = executor.submit(check_run_name, run_name)
        self.assertTrue(future.result())

    @unittest.skipIf(SHARED_POOL and WORLD_SIZE > 2, "shared-pool")
    def test_max_workers(self):
        executor = self.executor_type(max_workers=1)
        self.assertEqual(executor.num_workers, 1)
        self.assertEqual(executor.num_workers, executor._max_workers)
        executor.shutdown()
        self.assertEqual(executor.num_workers, 0)
        self.assertEqual(executor.num_workers, executor._max_workers)

    @unittest.skipIf(SHARED_POOL and WORLD_SIZE > 2, "shared-pool")
    def test_max_workers_environ(self):
        save = os.environ.get("MPI4PY_FUTURES_MAX_WORKERS")
        os.environ["MPI4PY_FUTURES_MAX_WORKERS"] = "1"
        try:
            executor = self.executor_type()
            executor.submit(time.sleep, 0).result()
            executor.shutdown()
            executor = self.executor_type()
            self.assertEqual(executor.num_workers, 1)
            executor.shutdown()
            self.assertEqual(executor.num_workers, 0)
        finally:
            del os.environ["MPI4PY_FUTURES_MAX_WORKERS"]
            if save is not None:
                os.environ["MPI4PY_FUTURES_MAX_WORKERS"] = save

    def test_max_workers_negative(self):
        for number in (0, -1):
            with self.assertRaises(ValueError):
                self.executor_type(max_workers=number)

    def test_get_comm_workers(self):
        executor = self.executor_type()
        num_workers = executor.submit(check_comm_workers).result()
        self.assertEqual(executor.num_workers, num_workers)
        self.assertRaises(RuntimeError, check_comm_workers)

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_use_pkl5_kwarg(self):
        executor = self.executor_type(use_pkl5=True)
        executor.submit(time.sleep, 0).result()
        executor.shutdown()

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_use_pkl5_environ(self):
        save = os.environ.get("MPI4PY_FUTURES_USE_PKL5")
        try:
            for value in ("false", "true"):
                os.environ["MPI4PY_FUTURES_USE_PKL5"] = value
                executor = self.executor_type()
                executor.submit(time.sleep, 0).result()
                executor.shutdown()
            with warnings.catch_warnings(record=True) as wlist:
                warnings.simplefilter("always")
                os.environ["MPI4PY_FUTURES_USE_PKL5"] = "foobar"
                executor = self.executor_type()
                executor.submit(time.sleep, 0).result()
                executor.shutdown()
            self.assertTrue(wlist)
            msg = wlist[0].message
            self.assertIsInstance(msg, RuntimeWarning)
            self.assertIn("foobar", msg.args[0])
        finally:
            del os.environ["MPI4PY_FUTURES_USE_PKL5"]
            if save is not None:
                os.environ["MPI4PY_FUTURES_USE_PKL5"] = save

    def test_initializer(self):
        executor = self.executor_type(
            initializer=time.sleep,
            initargs=(0,),
        )
        executor.submit(time.sleep, 0).result()

    def test_initializer_bad(self):
        with self.assertRaises(TypeError):
            self.executor_type(initializer=123)

    def test_initializer_error(self):
        executor = self.executor_type(
            initializer=sleep_and_raise,
            initargs=(0.2,),
        )
        executor.submit(time.sleep, 0).cancel()
        future = executor.submit(time.sleep, 0)
        with self.assertRaises(futures.BrokenExecutor):
            executor.submit(time.sleep, 0).result()
        with self.assertRaises(futures.BrokenExecutor):
            future.result()
        with self.assertRaises(futures.BrokenExecutor):
            executor.submit(time.sleep, 0)
        self.assertEqual(executor.num_workers, 0)

    def test_initializer_error_del(self):
        executor = self.executor_type(
            initializer=sleep_and_raise,
            initargs=(0.2,),
        )
        executor.bootup()
        del executor

    def test_initializer_error_del_nowait(self):
        executor = self.executor_type(
            initializer=sleep_and_raise,
            initargs=(1.2,),
        )
        executor.bootup(wait=False)
        executor.shutdown(wait=False)
        del executor


class ProcessPoolBootupTest(ProcessPoolMixin, unittest.TestCase):
    def _prime_executor(self):
        pass

    def test_bootup(self):
        executor = self.executor_type(1)
        executor.bootup()
        executor.bootup()
        executor.shutdown()
        with self.assertRaises(RuntimeError):
            executor.bootup()

    def test_bootup_wait(self):
        executor = self.executor_type(1)
        executor.bootup(wait=True)
        executor.bootup(wait=True)
        executor.shutdown(wait=True)
        with self.assertRaises(RuntimeError):
            executor.bootup(wait=True)

    def test_bootup_nowait(self):
        executor = self.executor_type(1)
        executor.bootup(wait=False)
        executor.bootup(wait=False)
        executor.shutdown(wait=False)
        with self.assertRaises(RuntimeError):
            executor.bootup(wait=False)
        executor.shutdown(wait=True)

    def test_bootup_nowait_wait(self):
        executor = self.executor_type(1)
        executor.bootup(wait=False)
        executor.bootup(wait=True)
        executor.shutdown()
        with self.assertRaises(RuntimeError):
            executor.bootup()

    def test_bootup_shutdown_nowait(self):
        executor = self.executor_type(1)
        executor.bootup(wait=False)
        executor.shutdown(wait=False)
        worker = executor._pool
        del executor
        worker.join()


class ExecutorShutdownTestMixin:
    def test_run_after_shutdown(self):
        self.executor.shutdown()
        with self.assertRaises(RuntimeError):
            self.executor.submit(pow, 2, 5)

    def test_hang_issue12364(self):
        fs = [self.executor.submit(time.sleep, 0.01) for _ in range(50)]
        self.executor.shutdown()
        for f in fs:
            f.result()


class ProcessPoolShutdownTest(
    ProcessPoolMixin, ExecutorShutdownTestMixin, unittest.TestCase
):
    def _prime_executor(self):
        pass

    def test_shutdown(self):
        executor = self.executor_type(max_workers=1)
        self.assertIsNone(executor._pool)
        self.assertFalse(executor._shutdown)
        executor.submit(mul, 21, 2)
        executor.submit(mul, 6, 7)
        executor.submit(mul, 3, 14)
        self.assertIsNotNone(executor._pool.thread)
        self.assertFalse(executor._shutdown)
        executor.shutdown(wait=False)
        self.assertIsNotNone(executor._pool.thread)
        self.assertTrue(executor._shutdown)
        executor.shutdown(wait=True)
        self.assertIsNone(executor._pool)
        self.assertTrue(executor._shutdown)

    def test_submit_shutdown_cancel(self):
        executor = self.executor_type(max_workers=1)
        executor.bootup()
        num_workers = executor.num_workers
        for _ in range(num_workers * 100):
            executor.submit(time.sleep, 0.1)
        fut = executor.submit(time.sleep, 0)
        executor.shutdown(wait=False, cancel_futures=False)
        self.assertFalse(fut.cancelled())
        executor.shutdown(wait=True, cancel_futures=True)
        self.assertTrue(fut.cancelled())

    def test_submit_shutdown_cancel_wait(self):
        executor = self.executor_type(max_workers=1)
        executor.bootup()
        num_workers = executor.num_workers
        fut1 = executor.submit(time.sleep, 0.1)
        for _ in range(num_workers * 100):
            executor.submit(time.sleep, 0.1)
        fut2 = executor.submit(time.sleep, 0)
        fut3 = executor.submit(time.sleep, 0)
        time.sleep(0.2)
        executor.shutdown(wait=False, cancel_futures=True)
        _done, not_done = futures.wait({fut1, fut2, fut3})
        self.assertEqual(len(not_done), 0)
        self.assertFalse(fut1.cancelled())
        self.assertTrue(fut2.cancelled())
        self.assertTrue(fut3.cancelled())
        executor.shutdown(wait=True, cancel_futures=True)

    def test_shutdown_cancel(self):
        executor = self.executor_type(max_workers=1)
        executor.bootup()
        executor._pool.cancel()
        executor.shutdown(wait=False, cancel_futures=False)
        executor.shutdown(wait=False, cancel_futures=False)
        executor.shutdown(wait=False, cancel_futures=True)
        executor.shutdown(wait=False, cancel_futures=True)
        executor.shutdown(wait=True, cancel_futures=True)
        executor.shutdown(wait=True, cancel_futures=True)

    def test_init_bootup_shutdown(self):
        executor = self.executor_type(max_workers=1)
        self.assertIsNone(executor._pool)
        self.assertFalse(executor._shutdown)
        executor.bootup()
        self.assertTrue(executor._pool.event.is_set())
        self.assertFalse(executor._shutdown)
        executor.shutdown()
        self.assertIsNone(executor._pool)
        self.assertTrue(executor._shutdown)

    def test_context_manager_shutdown(self):
        with self.executor_type(max_workers=1) as e:
            self.assertEqual(
                list(e.map(abs, range(-5, 5))), [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
            )
            threads = [e._pool.thread]
            queues = [e._pool.queue]
            events = [e._pool.event]

        for t in threads:
            t.join()
        for q in queues:
            with self.assertRaises(LookupError):
                q.pop()
        for e in events:
            self.assertTrue(e.is_set())

    def test_del_shutdown(self):
        executor = self.executor_type(max_workers=1)
        list(executor.map(abs, range(-5, 5)))
        threads = [executor._pool.thread]
        queues = [executor._pool.queue]
        events = [executor._pool.event]
        if hasattr(sys, "pypy_version_info"):
            executor.shutdown(False)
        else:
            del executor

        for t in threads:
            t.join()
        for q in queues:
            with self.assertRaises(LookupError):
                q.pop()
        for e in events:
            self.assertTrue(e.is_set())


class WaitTestMixin:
    def test_first_completed(self):
        future1 = self.executor.submit(mul, 21, 2)
        future2 = self.executor.submit(time.sleep, 0.25)

        done, not_done = futures.wait(
            [CANCELLED_FUTURE, future1, future2],
            return_when=futures.FIRST_COMPLETED,
        )

        self.assertEqual({future1}, done)
        self.assertEqual({CANCELLED_FUTURE, future2}, not_done)

    def test_first_completed_some_already_completed(self):
        future1 = self.executor.submit(time.sleep, 0.5)

        finished, pending = futures.wait(
            [CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE, future1],
            return_when=futures.FIRST_COMPLETED,
        )

        self.assertEqual(
            {CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE}, finished
        )
        self.assertEqual({future1}, pending)

    def test_first_exception(self):
        future1 = self.executor.submit(mul, 2, 21)
        future2 = self.executor.submit(sleep_and_raise, 0.25)
        future3 = self.executor.submit(time.sleep, 0.5)

        finished, pending = futures.wait(
            [future1, future2, future3], return_when=futures.FIRST_EXCEPTION
        )

        self.assertEqual({future1, future2}, finished)
        self.assertEqual({future3}, pending)

    def test_first_exception_some_already_complete(self):
        future1 = self.executor.submit(divmod, 21, 0)
        future2 = self.executor.submit(time.sleep, 0.5)

        finished, pending = futures.wait(
            [
                SUCCESSFUL_FUTURE,
                CANCELLED_FUTURE,
                CANCELLED_AND_NOTIFIED_FUTURE,
                future1,
                future2,
            ],
            return_when=futures.FIRST_EXCEPTION,
        )

        self.assertEqual(
            {SUCCESSFUL_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE, future1},
            finished,
        )
        self.assertEqual({CANCELLED_FUTURE, future2}, pending)

    def test_first_exception_one_already_failed(self):
        future1 = self.executor.submit(time.sleep, 0.25)

        finished, pending = futures.wait(
            [EXCEPTION_FUTURE, future1], return_when=futures.FIRST_EXCEPTION
        )

        self.assertEqual({EXCEPTION_FUTURE}, finished)
        self.assertEqual({future1}, pending)

    def test_all_completed(self):
        future1 = self.executor.submit(divmod, 2, 0)
        future2 = self.executor.submit(mul, 2, 21)

        finished, pending = futures.wait(
            [
                SUCCESSFUL_FUTURE,
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                future1,
                future2,
            ],
            return_when=futures.ALL_COMPLETED,
        )

        self.assertEqual(
            {
                SUCCESSFUL_FUTURE,
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                future1,
                future2,
            },
            finished,
        )
        self.assertEqual(set(), pending)

    def test_timeout(self):
        future1 = self.executor.submit(mul, 6, 7)
        future2 = self.executor.submit(time.sleep, 0.75)

        finished, pending = futures.wait(
            [
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
                future1,
                future2,
            ],
            timeout=0.5,
            return_when=futures.ALL_COMPLETED,
        )

        self.assertEqual(
            {
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
                future1,
            },
            finished,
        )
        self.assertEqual({future2}, pending)


class ProcessPoolWaitTest(ProcessPoolMixin, WaitTestMixin, unittest.TestCase):
    pass


class AsCompletedTestMixin:
    def test_no_timeout(self):
        future1 = self.executor.submit(mul, 2, 21)
        future2 = self.executor.submit(mul, 7, 6)

        completed = set(
            futures.as_completed([
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
                future1,
                future2,
            ])
        )
        self.assertEqual(
            {
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
                future1,
                future2,
            },
            completed,
        )

    def test_zero_timeout(self):
        future1 = self.executor.submit(time.sleep, 0.5)
        completed_futures = set()
        try:
            completed_futures.update(
                futures.as_completed(
                    [
                        CANCELLED_AND_NOTIFIED_FUTURE,
                        EXCEPTION_FUTURE,
                        SUCCESSFUL_FUTURE,
                        future1,
                    ],
                    timeout=0,
                )
            )
        except futures.TimeoutError:
            pass

        self.assertEqual(
            {
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
            },
            completed_futures,
        )

    def test_nonzero_timeout(self):
        future1 = self.executor.submit(time.sleep, 0.0)
        self.executor.submit(time.sleep, 0.5)
        completed_futures = set()
        try:
            completed_futures.update(
                futures.as_completed(
                    [
                        CANCELLED_AND_NOTIFIED_FUTURE,
                        EXCEPTION_FUTURE,
                        SUCCESSFUL_FUTURE,
                        future1,
                    ],
                    timeout=0.2,
                )
            )
        except futures.TimeoutError:
            pass

        self.assertEqual(
            {
                CANCELLED_AND_NOTIFIED_FUTURE,
                EXCEPTION_FUTURE,
                SUCCESSFUL_FUTURE,
                future1,
            },
            completed_futures,
        )

    def test_duplicate_futures(self):
        # Issue 20367. Duplicate futures should not raise exceptions or give
        # duplicate responses.
        future1 = self.executor.submit(time.sleep, 0.1)
        completed = list(futures.as_completed([future1, future1]))
        self.assertEqual(len(completed), 1)


class ProcessPoolAsCompletedTest(
    ProcessPoolMixin, AsCompletedTestMixin, unittest.TestCase
):
    pass


class ExecutorTestMixin:
    def test_submit(self):
        future = self.executor.submit(pow, 2, 8)
        self.assertEqual(256, future.result())

    def test_submit_keyword(self):
        future = self.executor.submit(mul, 2, y=8)
        self.assertEqual(16, future.result())
        future = self.executor.submit(mul, x=2, y=8)
        self.assertEqual(16, future.result())

    def test_submit_cancel(self):
        fs = []
        num_workers = self.executor.num_workers
        for _ in range(num_workers * 100):
            f = self.executor.submit(time.sleep, 0.1)
            fs.append(f)
        future = self.executor.submit(time.sleep, 0)
        future.cancel()
        self.assertTrue(future.cancelled())
        for f in fs:
            f.cancel()

    def test_map(self):
        self.assertEqual(
            list(self.executor.map(pow, range(10), range(10))),
            list(map(pow, range(10), range(10))),
        )

    def test_starmap(self):
        sequence = [(a, a) for a in range(10)]
        self.assertEqual(
            list(self.executor.starmap(pow, sequence)),
            list(map(pow, range(10), range(10))),
        )
        self.assertEqual(
            list(self.executor.starmap(pow, iter(sequence))),
            list(map(pow, range(10), range(10))),
        )

    def test_map_exception(self):
        i = self.executor.map(divmod, [1, 1, 1, 1], [2, 3, 0, 5])
        self.assertEqual(next(i), (0, 1))
        self.assertEqual(next(i), (0, 1))
        with self.assertRaises(ZeroDivisionError):
            next(i)

    def test_map_timeout(self):
        results = []
        try:
            for i in self.executor.map(time.sleep, [0, 0, 1], timeout=0.25):
                results.append(i)
        except futures.TimeoutError:
            pass
        else:
            self.fail("expected TimeoutError")

        self.assertEqual([None, None], results)

    def test_map_timeout_one(self):
        results = []
        for i in self.executor.map(time.sleep, [0, 0, 0], timeout=1):
            results.append(i)
        self.assertEqual([None, None, None], results)


class ProcessPoolExecutorTest(
    ProcessPoolMixin, ExecutorTestMixin, unittest.TestCase
):
    def test_map_chunksize(self):
        ref = list(map(pow, range(40), range(40)))
        self.assertEqual(
            list(self.executor.map(pow, range(40), range(40), chunksize=6)),
            ref,
        )
        self.assertEqual(
            list(self.executor.map(pow, range(40), range(40), chunksize=50)),
            ref,
        )
        self.assertEqual(
            list(self.executor.map(pow, range(40), range(40), chunksize=40)),
            ref,
        )
        with self.assertRaises(ValueError):
            list(self.executor.map(pow, range(40), range(40), chunksize=-1))

    def test_starmap_chunksize(self):
        ref = list(map(pow, range(40), range(40)))
        sequence = [(a, a) for a in range(40)]
        self.assertEqual(
            list(self.executor.starmap(pow, sequence, chunksize=6)), ref
        )
        self.assertEqual(
            list(self.executor.starmap(pow, sequence, chunksize=50)), ref
        )
        self.assertEqual(
            list(self.executor.starmap(pow, sequence, chunksize=40)), ref
        )
        self.assertEqual(
            list(self.executor.starmap(pow, iter(sequence), chunksize=6)), ref
        )
        self.assertEqual(
            list(self.executor.starmap(pow, iter(sequence), chunksize=50)), ref
        )
        self.assertEqual(
            list(self.executor.starmap(pow, iter(sequence), chunksize=40)), ref
        )

        with self.assertRaises(ValueError):
            list(self.executor.starmap(pow, sequence, chunksize=-1))

    def test_map_buffersize(self):
        ref = list(map(pow, range(10), range(10)))
        for bs in (1, 2, 9, 10, 11):
            for cs in (1, 2, 9, 10, 11):
                self.assertEqual(
                    list(
                        self.executor.map(
                            pow,
                            range(10),
                            range(10),
                            chunksize=cs,
                            buffersize=bs,
                        )
                    ),
                    ref,
                )
        with self.assertRaises(TypeError):
            self.executor.map(
                pow,
                range(10),
                range(10),
                buffersize=str(1),
            )
        with self.assertRaises(ValueError):
            self.executor.map(
                pow,
                range(10),
                range(10),
                buffersize=-1,
            )
        with self.assertRaises(ValueError):
            self.executor.map(
                pow,
                range(10),
                range(10),
                buffersize=1,
                unordered=True,
            )

    def test_map_unordered(self):
        map_unordered = functools.partial(self.executor.map, unordered=True)
        self.assertEqual(
            set(map_unordered(pow, range(10), range(10))),
            set(map(pow, range(10), range(10))),
        )

    def test_map_unordered_timeout(self):
        map_unordered = functools.partial(self.executor.map, unordered=True)
        num_workers = self.executor.num_workers
        results = []
        try:
            args = [1] + [0] * (num_workers - 1)
            for i in map_unordered(time.sleep, args, timeout=0.25):
                results.append(i)
        except futures.TimeoutError:
            pass
        else:
            self.fail("expected TimeoutError")

        self.assertEqual([None] * (num_workers - 1), results)

    def test_map_unordered_timeout_one(self):
        map_unordered = functools.partial(self.executor.map, unordered=True)
        results = []
        for i in map_unordered(time.sleep, [0, 0, 0], timeout=1):
            results.append(i)
        self.assertEqual([None, None, None], results)

    def test_map_unordered_exception(self):
        map_unordered = functools.partial(self.executor.map, unordered=True)
        i = map_unordered(divmod, [1, 1, 1, 1], [2, 3, 0, 5])
        try:
            self.assertEqual(next(i), (0, 1))
        except ZeroDivisionError:
            return

    def test_map_unordered_chunksize(self):
        map_unordered = functools.partial(self.executor.map, unordered=True)
        ref = set(map(pow, range(40), range(40)))
        self.assertEqual(
            set(map_unordered(pow, range(40), range(40), chunksize=6)), ref
        )
        self.assertEqual(
            set(map_unordered(pow, range(40), range(40), chunksize=50)), ref
        )
        self.assertEqual(
            set(map_unordered(pow, range(40), range(40), chunksize=40)), ref
        )
        with self.assertRaises(ValueError):
            set(map_unordered(pow, range(40), range(40), chunksize=-1))


class ProcessPoolSubmitTest(unittest.TestCase):
    @unittest.skipIf(MPI.get_vendor()[0] == "Microsoft MPI", "msmpi")
    def test_multiple_executors(self):
        executor1 = futures.MPIPoolExecutor(1).bootup(wait=True)
        executor2 = futures.MPIPoolExecutor(1).bootup(wait=True)
        executor3 = futures.MPIPoolExecutor(1).bootup(wait=True)
        fs1 = [executor1.submit(abs, i) for i in range(100, 200)]
        fs2 = [executor2.submit(abs, i) for i in range(200, 300)]
        fs3 = [executor3.submit(abs, i) for i in range(300, 400)]
        futures.wait(fs3 + fs2 + fs1)
        for i, f in enumerate(fs1):
            self.assertEqual(f.result(), i + 100)
        for i, f in enumerate(fs2):
            self.assertEqual(f.result(), i + 200)
        for i, f in enumerate(fs3):
            self.assertEqual(f.result(), i + 300)
        executor1 = executor2 = executor3 = None

    def test_mpi_serialized_support(self):
        futures._core.setup_mpi_threads()
        serialized = futures._core.serialized
        lock_save = serialized.lock
        try:
            if lock_save is None:
                serialized.lock = threading.Lock()
                executor = futures.MPIPoolExecutor(1).bootup()
                executor.submit(abs, 0).result()
                executor.shutdown()
                serialized.lock = lock_save
            else:
                serialized.lock = None
                with lock_save:
                    executor = futures.MPIPoolExecutor(1).bootup()
                    executor.submit(abs, 0).result()
                    executor.shutdown()
                serialized.lock = lock_save
        finally:
            serialized.lock = lock_save

    def test_shared_executors(self):
        if not SHARED_POOL:
            return
        executors = [futures.MPIPoolExecutor() for _ in range(16)]
        fs = []
        for i in range(128):
            fs.extend(
                e.submit(abs, i * 16 + j) for j, e in enumerate(executors)
            )
        self.assertEqual(sorted(f.result() for f in fs), list(range(16 * 128)))
        world_size = MPI.COMM_WORLD.Get_size()
        num_workers = max(1, world_size - 1)
        for e in executors:
            self.assertEqual(e.num_workers, num_workers)
        del e, executors


def inout(arg):
    return arg


class GoodPickle:
    def __init__(self, value=0):
        self.value = value
        self.pickled = False
        self.unpickled = False

    def __getstate__(self):
        self.pickled = True
        return (self.value,)

    def __setstate__(self, state):
        self.unpickled = True
        self.value = state[0]


class BadPickle:
    def __init__(self):
        self.pickled = False

    def __getstate__(self):
        self.pickled = True
        _ = 1 / 0

    def __setstate__(self, state):
        pass


class BadUnpickle:
    def __init__(self):
        self.pickled = False

    def __getstate__(self):
        self.pickled = True
        return (None,)

    def __setstate__(self, state):
        if state[0] is not None:
            raise ValueError
        _ = 1 / 0


@unittest.skipIf(SHARED_POOL and WORLD_SIZE == 1, "shared-pool")
class ProcessPoolPickleTest(unittest.TestCase):
    def setUp(self):
        self.executor = futures.MPIPoolExecutor(1)

    def tearDown(self):
        self.executor.shutdown()

    def test_good_pickle(self):
        o = GoodPickle(42)
        r = self.executor.submit(inout, o).result()
        self.assertEqual(o.value, r.value)
        self.assertTrue(o.pickled)
        self.assertTrue(r.unpickled)

        r = self.executor.submit(GoodPickle, 77).result()
        self.assertEqual(r.value, 77)
        self.assertTrue(r.unpickled)

    def test_bad_pickle(self):
        o = BadPickle()
        self.assertFalse(o.pickled)
        f = self.executor.submit(inout, o)
        with self.assertRaises(ZeroDivisionError):
            f.result()
        self.assertTrue(o.pickled)

        f = self.executor.submit(BadPickle)
        with self.assertRaises(ZeroDivisionError):
            f.result()

        f = self.executor.submit(abs, 42)
        self.assertEqual(f.result(), 42)

    def test_bad_unpickle(self):
        o = BadUnpickle()
        self.assertFalse(o.pickled)
        f = self.executor.submit(inout, o)
        with self.assertRaises(ZeroDivisionError):
            f.result()
        self.assertTrue(o.pickled)

        f = self.executor.submit(BadUnpickle)
        with self.assertRaises(ZeroDivisionError):
            f.result()

        f = self.executor.submit(abs, 42)
        self.assertEqual(f.result(), 42)

    def test_exc_pickle(self):
        o = BadPickle()
        f = self.executor.submit(inout, o)
        exc = f.exception()
        self.assertIsInstance(exc, ZeroDivisionError)
        cause = exc.__cause__
        self.assertIsNone(cause)

    def test_exc_unpickle(self):
        o = BadUnpickle()
        f = self.executor.submit(inout, o)
        exc = f.exception()
        self.assertIsInstance(exc, ZeroDivisionError)
        cause = exc.__cause__
        self.assertIsInstance(cause, futures._core.RemoteTraceback)


class MPICommExecutorTest(unittest.TestCase):
    MPICommExecutor = futures.MPICommExecutor

    def test_default(self):
        with self.MPICommExecutor() as executor:
            if executor is not None:
                executor.bootup()
                future1 = executor.submit(time.sleep, 0)
                future2 = executor.submit(time.sleep, 0)
                executor.shutdown()
                self.assertIsNone(future1.result())
                self.assertIsNone(future2.result())

    def test_self(self):
        with self.MPICommExecutor(MPI.COMM_SELF) as executor:
            future = executor.submit(time.sleep, 0)
            self.assertIsNone(future.result())
            self.assertIsNone(future.exception())

            future = executor.submit(sleep_and_raise, 0)
            with self.assertRaises(RuntimeError):
                future.result()
            self.assertEqual(RuntimeError, type(future.exception()))

            list(executor.map(time.sleep, [0, 0]))
            list(executor.map(time.sleep, [0, 0], timeout=1))
            iterator = executor.map(time.sleep, [0.2, 0], timeout=0)
            with self.assertRaises(futures.TimeoutError):
                list(iterator)

    def test_args(self):
        with self.MPICommExecutor(MPI.COMM_SELF) as executor:
            self.assertIsNotNone(executor)
        with self.MPICommExecutor(MPI.COMM_SELF, 0) as executor:
            self.assertIsNotNone(executor)

    def test_kwargs(self):
        with self.MPICommExecutor(comm=MPI.COMM_SELF) as executor:
            self.assertIsNotNone(executor)
        with self.MPICommExecutor(comm=MPI.COMM_SELF, root=0) as executor:
            self.assertIsNotNone(executor)

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_arg_root(self):
        comm = MPI.COMM_WORLD
        rank = comm.Get_rank()
        for root in range(comm.Get_size()):
            with self.MPICommExecutor(comm, root) as executor:
                if rank == root:
                    self.assertIsNotNone(executor)
                else:
                    self.assertIsNone(executor)
            with self.MPICommExecutor(root=root) as executor:
                if rank == root:
                    self.assertIsNotNone(executor)
                else:
                    self.assertIsNone(executor)

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_arg_bad_root(self):
        size = MPI.COMM_WORLD.Get_size()
        with self.assertRaises(ValueError):
            self.MPICommExecutor(root=-size)
        with self.assertRaises(ValueError):
            self.MPICommExecutor(root=-1)
        with self.assertRaises(ValueError):
            self.MPICommExecutor(root=+size)

    @unittest.skipIf(SHARED_POOL, "shared-pool")
    def test_arg_bad_comm(self):
        if MPI.COMM_WORLD.Get_size() == 1:
            return
        intercomm, intracomm = futures._core.comm_split(MPI.COMM_WORLD, 0)
        try:
            with self.assertRaises(ValueError):
                self.MPICommExecutor(intercomm)
        finally:
            intercomm.Free()
            if intracomm:
                intracomm.Free()

    def test_with_bad(self):
        mpicommexecutor = self.MPICommExecutor(MPI.COMM_SELF)
        with mpicommexecutor:
            try:
                with mpicommexecutor:
                    pass
            except RuntimeError:
                pass
            else:
                self.fail("expected RuntimeError")

    def test_initializer(self):
        mpicommexecutor = self.MPICommExecutor(
            initializer=time.sleep,
            initargs=(0,),
        )
        with mpicommexecutor as executor:
            if executor is not None:
                executor.bootup()
                del executor
        with mpicommexecutor as executor:
            if executor is not None:
                executor.submit(time.sleep, 0).result()

    def test_initializer_error(self):
        mpicommexecutor = self.MPICommExecutor(
            initializer=sleep_and_raise,
            initargs=(0.2,),
        )
        with mpicommexecutor as executor:
            if executor is not None:
                executor.submit(time.sleep, 0).cancel()
                future = executor.submit(time.sleep, 0)
                with self.assertRaises(futures.BrokenExecutor):
                    executor.submit(time.sleep, 0).result()
                with self.assertRaises(futures.BrokenExecutor):
                    future.result()

    def test_initializer_error_del(self):
        mpicommexecutor = self.MPICommExecutor(
            initializer=sleep_and_raise,
            initargs=(0.2,),
        )
        with mpicommexecutor as executor:
            if executor is not None:
                executor.bootup()
                del executor

    def test_initializer_error_del_nowait(self):
        mpicommexecutor = self.MPICommExecutor(
            initializer=sleep_and_raise,
            initargs=(0.2,),
        )
        with mpicommexecutor as executor:
            if executor is not None:
                executor.bootup(wait=False)
                executor.shutdown(wait=False)
                del executor

    def test_get_comm_workers(self):
        for _comm in (MPI.COMM_SELF, MPI.COMM_WORLD):
            with self.MPICommExecutor(MPI.COMM_SELF) as executor:
                num_workers = executor.submit(check_comm_workers).result()
                self.assertEqual(executor.num_workers, num_workers)
        self.assertRaises(RuntimeError, check_comm_workers)


class ThreadPoolMixin(ExecutorMixin):
    executor_type = futures.ThreadPoolExecutor


class ThreadPoolTest(
    ThreadPoolMixin,
    ExecutorTestMixin,
    ExecutorShutdownTestMixin,
    unittest.TestCase,
):
    pass


from mpi4py.futures.aplus import ThenableFuture  # noqa: E402


class ThenTest(unittest.TestCase):
    assert_ = unittest.TestCase.assertTrue

    def test_cancel_base(self):
        base_f = ThenableFuture()
        new_f = base_f.then()

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.cancel()
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(base_f.cancelled())
        self.assertTrue(new_f.cancelled())

    def test_cancel_new(self):
        base_f = ThenableFuture()
        new_f = base_f.then()

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        new_f.cancel()
        self.assertTrue(not base_f.done())
        self.assertTrue(new_f.done())

        base_f.set_result(1)
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.cancelled())

    def test_then_multiple(self):
        base_f = ThenableFuture()
        new_f1 = base_f.then()
        new_f2 = base_f.then()
        new_f3 = base_f.then()

        self.assertIsNot(base_f, new_f1)
        self.assertIsNot(base_f, new_f2)
        self.assertIsNot(base_f, new_f3)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f1.done())
        self.assertTrue(not new_f2.done())
        self.assertTrue(not new_f3.done())

        base_f.set_result("done")
        self.assertTrue(base_f.done())
        self.assertTrue(new_f1.done())
        self.assertTrue(new_f2.done())
        self.assertTrue(new_f3.done())

        self.assertTrue(not new_f1.exception())
        self.assertTrue(not new_f2.exception())
        self.assertTrue(not new_f3.exception())
        self.assertEqual(new_f1.result(), "done")
        self.assertEqual(new_f2.result(), "done")
        self.assertEqual(new_f3.result(), "done")

    def test_no_callbacks_and_success(self):
        base_f = ThenableFuture()
        new_f = base_f.then()

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result("done")
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(not new_f.exception())
        self.assertEqual(new_f.result(), "done")

    def test_no_callbacks_and_failure(self):
        class MyException(Exception):
            pass

        base_f = ThenableFuture()
        new_f = base_f.then()

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(MyException("sad"))
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(MyException) as catcher:
            new_f.result()
        self.assertEqual(catcher.exception.args[0], "sad")

    def test_success_callback_and_success(self):
        base_f = ThenableFuture()
        new_f = base_f.then(lambda result: result + " manipulated")

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result("done")
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(not new_f.exception())
        self.assertEqual(new_f.result(), "done manipulated")

    def test_err_callback_and_failure_repackage(self):
        class MyException(Exception):
            pass

        class MyRepackagedException(Exception):
            pass

        class NotMatched(Exception):
            pass

        def on_failure(ex):
            if isinstance(ex, MyException):
                return MyRepackagedException(ex.args[0] + " repackaged")
            else:
                return NotMatched("?")

        base_f = ThenableFuture()
        new_f = base_f.then(None, on_failure)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(MyException("sad"))
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(MyRepackagedException) as catcher:
            new_f.result()
        self.assertEqual(catcher.exception.args[0], "sad repackaged")

    def test_err_callback_and_failure_raised(self):
        class MyException(Exception):
            pass

        class MyRepackagedException(Exception):
            pass

        def raise_something_else(ex):
            raise MyRepackagedException(ex.args[0] + " repackaged")

        base_f = ThenableFuture()
        new_f = base_f.then(None, raise_something_else)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(MyException("sad"))
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(MyRepackagedException) as catcher:
            new_f.result()
        self.assertEqual(catcher.exception.args[0], "sad repackaged")

    def test_err_callback_convert_to_success(self):
        class MyException(Exception):
            pass

        class NotMatched(Exception):
            pass

        def on_failure(ex):
            if isinstance(ex, MyException):
                return ex.args[0] + " repackaged"
            else:
                return NotMatched("?")

        base_f = ThenableFuture()
        new_f = base_f.catch(on_failure)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(MyException("sad"))
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(not new_f.exception())
        self.assertEqual(new_f.result(), "sad repackaged")

    def test_err_catch_ignore(self):
        base_f = ThenableFuture()
        new_f = base_f.catch()

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(Exception("sad"))
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertIsNone(new_f.exception())
        self.assertIsNone(new_f.result())

    def test_success_callback_and_failure_raised(self):
        class MyException(Exception):
            pass

        def raise_something_else(value):
            raise MyException(value + " repackaged")

        base_f = ThenableFuture()
        new_f = base_f.then(raise_something_else)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result("sad")
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(MyException) as catcher:
            new_f.result()
        assert catcher.exception.args[0] == "sad repackaged"

    def test_chained_success_callback_and_success(self):
        def transform(value):
            f = ThenableFuture()
            if value < 5:
                f.set_result(transform(value + 1))
            else:
                f.set_result(value)
            return f

        base_f = ThenableFuture()
        new_f = base_f.then(transform)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result(1)
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(not new_f.exception())
        self.assertEqual(new_f.result(), 5)

    def test_chained_failure_callback_and_success(self):
        def transform(exc):
            self.assertIsInstance(exc, RuntimeError)
            f = ThenableFuture()
            f.set_result(5)
            return f

        base_f = ThenableFuture()
        new_f = base_f.catch(transform)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_exception(RuntimeError())
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(not new_f.exception())
        self.assertEqual(new_f.result(), 5)

    def test_detect_cycle_chain(self):
        f1 = ThenableFuture()
        f2 = ThenableFuture()
        chain = [f1, f2, f1]

        def transform(a):
            try:
                f = chain.pop(0)
                r = transform(a)
                f.__init__()
                f.set_result(r)
            except IndexError:
                return 42
            else:
                return f

        base_f = ThenableFuture()
        new_f = base_f.then(transform)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result(1)
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(RuntimeError) as catcher:
            new_f.result()
        self.assertIn(
            "chain cycle detected",
            catcher.exception.args[0],
        )

    def test_detect_self_chain(self):
        base_f = ThenableFuture()
        new_f = base_f.then(lambda _: new_f)

        self.assertIsNot(base_f, new_f)
        self.assertTrue(not base_f.done())
        self.assertTrue(not new_f.done())

        base_f.set_result(1)
        self.assertTrue(base_f.done())
        self.assertTrue(new_f.done())

        self.assertTrue(new_f.exception())
        with self.assertRaises(RuntimeError) as catcher:
            new_f.result()
        self.assertIn(
            "chain cycle detected",
            catcher.exception.args[0],
        )


class CollectTest(unittest.TestCase):
    def test_empty(self):
        future = futures.collect([])
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertEqual(future.result(), [])

    def test_item_success(self):
        fs = [futures.Future() for _ in range(5)]
        future = futures.collect(fs)
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertFalse(future.done())
        for i in range(5):
            fs[i].set_result(i)
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertEqual(future.result(), list(range(5)))

    def test_item_failure(self):
        fs = [futures.Future() for _ in range(5)]
        future = futures.collect(fs)
        for i in range(2, 4):
            fs[i].set_result(i)
        fs[-1].set_exception(RuntimeError())
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertIsInstance(future.exception(), RuntimeError)
        for i in range(2):
            self.assertTrue(fs[i].cancelled())
        for i in range(2, 4):
            self.assertFalse(fs[i].cancelled())
        self.assertFalse(fs[-1].cancelled())

    def test_item_done(self):
        fs = [futures.Future() for _ in range(5)]
        for i in range(5):
            fs[i].set_result(i)
        future = futures.collect(fs)
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertEqual(future.result(), list(range(5)))

    def test_item_cancel(self):
        fs = [futures.Future() for _ in range(5)]
        future = futures.collect(fs)
        for i in range(2, 4):
            fs[i].set_result(i)
        fs[-1].cancel()
        self.assertTrue(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        for i in range(2):
            self.assertTrue(fs[i].cancelled())
        for i in range(2, 4):
            self.assertFalse(fs[i].cancelled())
        self.assertTrue(fs[-1].cancelled())

    def test_cancel(self):
        fs = [futures.Future() for _ in range(5)]
        future = futures.collect(fs)
        future.cancel()
        for f in fs:
            self.assertTrue(f.cancelled())

    def test_cancel_pending(self):
        class MyFuture(futures.Future):
            def cancel(self):
                pass

        fs = [MyFuture() for _ in range(5)]
        future = futures.collect(fs)
        self.assertIs(type(future), MyFuture)
        super(MyFuture, future).cancel()
        for f in fs:
            self.assertFalse(f.cancelled())
            f.set_result(None)


class ComposeTest(unittest.TestCase):
    def test_result(self):
        base = futures.Future()
        future = futures.compose(base)
        self.assertIs(type(future), type(base))
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertFalse(future.done())
        base.set_result(42)
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertEqual(future.result(), 42)

    def test_except(self):
        base = futures.Future()
        future = futures.compose(base)
        self.assertIs(type(future), type(base))
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertFalse(future.done())
        base.set_exception(RuntimeError(42))
        self.assertFalse(future.cancelled())
        self.assertFalse(future.running())
        self.assertTrue(future.done())
        self.assertIs(type(future.exception()), RuntimeError)
        self.assertEqual(future.exception().args, (42,))

    def test_cancel_new(self):
        base = futures.Future()
        future = futures.compose(base)
        base.cancel()
        self.assertTrue(future.cancelled())

    def test_cancel_old(self):
        base = futures.Future()
        future = futures.compose(base)
        future.cancel()
        self.assertTrue(base.cancelled())

    def test_result_hook(self):
        base = futures.Future()
        future = futures.compose(base, int)
        base.set_result("42")
        self.assertEqual(future.result(), 42)

    def test_result_hook_failure(self):
        base = futures.Future()
        future = futures.compose(base, resulthook=lambda _: 1 / 0)
        base.set_result(42)
        self.assertIs(type(future.exception()), ZeroDivisionError)

    def test_except_hook(self):
        base = futures.Future()
        future = futures.compose(base, excepthook=lambda exc: exc.args[0])
        base.set_exception(RuntimeError(42))
        self.assertEqual(future.result(), 42)

    def test_except_hook_except(self):
        base = futures.Future()
        future = futures.compose(
            base, excepthook=lambda exc: RuntimeError(exc.args[0])
        )
        base.set_exception(ValueError(42))
        self.assertIs(type(future.exception()), RuntimeError)
        self.assertEqual(future.exception().args, (42,))

    def test_except_hook_failure(self):
        base = futures.Future()
        future = futures.compose(base, excepthook=lambda _: 1 / 0)
        base.set_exception(ValueError(42))
        self.assertIs(type(future.exception()), ZeroDivisionError)


SKIP_POOL_TEST = testutil.disable_mpi_spawn()

if SHARED_POOL:
    del ProcessPoolInitTest.test_init_sys_flags
    del ProcessPoolInitTest.test_init_globals
    del ProcessPoolInitTest.test_use_pkl5_kwarg
    del ProcessPoolInitTest.test_use_pkl5_environ
    if WORLD_SIZE == 1:
        del ProcessPoolInitTest.test_run_name
    if WORLD_SIZE > 2:
        del ProcessPoolInitTest.test_max_workers
        del ProcessPoolInitTest.test_max_workers_environ
    if WORLD_SIZE == 1:
        del ProcessPoolPickleTest
    del MPICommExecutorTest.test_arg_root
    del MPICommExecutorTest.test_arg_bad_root
    del MPICommExecutorTest.test_arg_bad_comm
elif WORLD_SIZE > 1 or SKIP_POOL_TEST:
    del ProcessPoolInitTest
    del ProcessPoolBootupTest
    del ProcessPoolShutdownTest
    del ProcessPoolWaitTest
    del ProcessPoolAsCompletedTest
    del ProcessPoolExecutorTest
    del ProcessPoolSubmitTest
    del ProcessPoolPickleTest
if not SHARED_POOL:
    del SharedPoolInitTest


if __name__ == "__main__":
    unittest.main()