File: helper.py

package info (click to toggle)
dput 0.12.1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 812 kB
  • ctags: 1,191
  • sloc: python: 10,349; sh: 140; makefile: 88
file content (1719 lines) | stat: -rw-r--r-- 55,713 bytes parent folder | download
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
# -*- coding: utf-8; -*-
#
# test/helper.py
# Part of ‘dput’, a Debian package upload toolkit.
#
# This is free software, and you are welcome to redistribute it under
# certain conditions; see the end of this file for copyright
# information, grant of license, and disclaimer of warranty.

""" Helper functionality for Dput test suite. """

from __future__ import (absolute_import, unicode_literals)

import sys

if sys.version_info >= (3, 3):
    import builtins
    import collections.abc as collections_abc
    import configparser
    from io import StringIO as StringIO
    import unittest
    import unittest.mock as mock
elif sys.version_info >= (3, 0):
    raise RuntimeError("Python 3 earlier than 3.3 is not supported.")
elif sys.version_info >= (2, 7):
    # Python 2 standard library.
    import __builtin__ as builtins
    import collections as collections_abc
    import ConfigParser as configparser
    from StringIO import StringIO as BaseStringIO
    # Third-party backport of Python 3 unittest improvements.
    import unittest2 as unittest
    # Third-party mock library.
    import mock
else:
    raise RuntimeError("Python earlier than 2.7 is not supported.")

import base64
import collections
import errno
import functools
import io
import itertools
import os
import os.path
import pwd
import shlex
import shutil
import signal
import subprocess
import tempfile
import time
import weakref


__metaclass__ = type

try:
    # Python 2 types.
    basestring
    unicode
except NameError:
    # Alias for Python 3 types.
    basestring = str
    unicode = str


def make_unique_slug(testcase):
    """ Make a unique slug for the test case. """
    text = base64.b64encode(
            testcase.getUniqueString().encode('utf-8')
            ).decode('utf-8')
    result = text[-30:]
    return result


try:
    StringIO
except NameError:
    # We don't yet have the StringIO we want. Create it.

    class StringIO(BaseStringIO, object):
        """ StringIO with a context manager. """

        def __enter__(self):
            return self

        def __exit__(self, *args):
            self.close()
            return False

        def readable(self):
            return True

        def writable(self):
            return True

        def seekable(self):
            return True


def patch_stdout(testcase):
    """ Patch `sys.stdout` for the specified test case. """
    patcher = mock.patch.object(
            sys, "stdout", wraps=StringIO())
    patcher.start()
    testcase.addCleanup(patcher.stop)


def patch_stderr(testcase):
    """ Patch `sys.stderr` for the specified test case. """
    patcher = mock.patch.object(
            sys, "stderr", wraps=StringIO())
    patcher.start()
    testcase.addCleanup(patcher.stop)


def patch_signal_signal(testcase):
    """ Patch `signal.signal` for the specified test case. """
    func_patcher = mock.patch.object(signal, "signal", autospec=True)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


class FakeSystemExit(Exception):
    """ Fake double for `SystemExit` exception. """


EXIT_STATUS_SUCCESS = 0
EXIT_STATUS_FAILURE = 1
EXIT_STATUS_COMMAND_NOT_FOUND = 127


def patch_sys_exit(testcase):
    """ Patch `sys.exit` for the specified test case. """
    func_patcher = mock.patch.object(
            sys, "exit", autospec=True,
            side_effect=FakeSystemExit())
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_sys_argv(testcase):
    """ Patch the `sys.argv` sequence for the test case. """
    if not hasattr(testcase, 'progname'):
        testcase.progname = make_unique_slug(testcase)
    if not hasattr(testcase, 'sys_argv'):
        testcase.sys_argv = [testcase.progname]
    patcher = mock.patch.object(
            sys, "argv",
            new=list(testcase.sys_argv))
    patcher.start()
    testcase.addCleanup(patcher.stop)


def patch_system_interfaces(testcase):
    """ Patch system interfaces that are disruptive to the test runner. """
    patch_stdout(testcase)
    patch_stderr(testcase)
    patch_sys_exit(testcase)
    patch_sys_argv(testcase)


def patch_time_time(testcase, values=None):
    """ Patch the `time.time` function for the specified test case.

        :param testcase: The `TestCase` instance for binding to the patch.
        :param values: An iterable to provide return values.
        :return: None.

        """
    if values is None:
        values = itertools.count()

    def generator_fake_time():
        while True:
            yield next(values)

    func_patcher = mock.patch.object(time, "time", autospec=True)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)

    time.time.side_effect = generator_fake_time()


def patch_os_environ(testcase):
    """ Patch the `os.environ` mapping. """
    if not hasattr(testcase, 'os_environ'):
        testcase.os_environ = {}
    patcher = mock.patch.object(os, "environ", new=testcase.os_environ)
    patcher.start()
    testcase.addCleanup(patcher.stop)


def patch_os_getpid(testcase):
    """ Patch `os.getpid` for the specified test case. """
    func_patcher = mock.patch.object(os, "getpid", autospec=True)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_getuid(testcase):
    """ Patch the `os.getuid` function. """
    if not hasattr(testcase, 'os_getuid_return_value'):
        testcase.os_getuid_return_value = testcase.getUniqueInteger()
    func_patcher = mock.patch.object(
            os, "getuid", autospec=True,
            return_value=testcase.os_getuid_return_value)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


PasswdEntry = collections.namedtuple(
        "PasswdEntry",
        "pw_name pw_passwd pw_uid pw_gid pw_gecos pw_dir pw_shell")


def patch_pwd_getpwuid(testcase):
    """ Patch the `pwd.getpwuid` function. """
    if not hasattr(testcase, 'pwd_getpwuid_return_value'):
        testcase.pwd_getpwuid_return_value = PasswdEntry(
                pw_name=make_unique_slug(testcase),
                pw_passwd=make_unique_slug(testcase),
                pw_uid=testcase.getUniqueInteger(),
                pw_gid=testcase.getUniqueInteger(),
                pw_gecos=testcase.getUniqueString(),
                pw_dir=tempfile.mktemp(),
                pw_shell=tempfile.mktemp())
    if not isinstance(testcase.pwd_getpwuid_return_value, pwd.struct_passwd):
        pwent = pwd.struct_passwd(testcase.pwd_getpwuid_return_value)
    else:
        pwent = testcase.pwd_getpwuid_return_value
    func_patcher = mock.patch.object(
            pwd, "getpwuid", autospec=True,
            return_value=pwent)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_path_exists(testcase):
    """ Patch `os.path.exists` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_path_exists = os.path.exists

    def fake_os_path_exists(path):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_path_exists_scenario.call_hook()
        else:
            result = orig_os_path_exists(path)
        return result

    func_patcher = mock.patch.object(
            os.path, "exists", autospec=True,
            side_effect=fake_os_path_exists)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_access(testcase):
    """ Patch `os.access` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_access = os.access

    def fake_os_access(path, mode):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_access_scenario.call_hook(mode)
        else:
            result = orig_os_access(path, mode)
        return result

    func_patcher = mock.patch.object(
            os, "access", autospec=True,
            side_effect=fake_os_access)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


StatResult = collections.namedtuple(
        'StatResult', [
            'st_mode',
            'st_ino', 'st_dev', 'st_nlink',
            'st_uid', 'st_gid',
            'st_size',
            'st_atime', 'st_mtime', 'st_ctime',
            ])


def patch_os_stat(testcase):
    """ Patch `os.stat` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_stat = os.stat

    def fake_os_stat(path):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_stat_scenario.call_hook()
        else:
            result = orig_os_stat(path)
        return result

    func_patcher = mock.patch.object(
            os, "stat", autospec=True,
            side_effect=fake_os_stat)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_lstat(testcase):
    """ Patch `os.lstat` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_lstat = os.lstat

    def fake_os_lstat(path):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_lstat_scenario.call_hook()
        else:
            result = orig_os_lstat(path)
        return result

    func_patcher = mock.patch.object(
            os, "lstat", autospec=True,
            side_effect=fake_os_lstat)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_unlink(testcase):
    """ Patch `os.unlink` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_unlink = os.unlink

    def fake_os_unlink(path):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_unlink_scenario.call_hook()
        else:
            result = orig_os_unlink(path)
        return result

    func_patcher = mock.patch.object(
            os, "unlink", autospec=True,
            side_effect=fake_os_unlink)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_rmdir(testcase):
    """ Patch `os.rmdir` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_os_rmdir = os.rmdir

    def fake_os_rmdir(path):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.os_rmdir_scenario.call_hook()
        else:
            result = orig_os_rmdir(path)
        return result

    func_patcher = mock.patch.object(
            os, "rmdir", autospec=True,
            side_effect=fake_os_rmdir)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_shutil_rmtree(testcase):
    """ Patch `shutil.rmtree` behaviour for this test case.

        When the patched function is called, the registry of
        `FileDouble` instances for this test case will be used to get
        the instance for the path specified.

        """
    orig_shutil_rmtree = os.rmdir

    def fake_shutil_rmtree(path, ignore_errors=False, onerror=None):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.shutil_rmtree_scenario.call_hook()
        else:
            result = orig_shutil_rmtree(path)
        return result

    func_patcher = mock.patch.object(
            shutil, "rmtree", autospec=True,
            side_effect=fake_shutil_rmtree)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_tempfile_mkdtemp(testcase):
    """ Patch the `tempfile.mkdtemp` function for this test case. """
    if not hasattr(testcase, 'tempfile_mkdtemp_file_double'):
        testcase.tempfile_mkdtemp_file_double = FileDouble(tempfile.mktemp())

    double = testcase.tempfile_mkdtemp_file_double
    double.set_os_unlink_scenario('okay')
    double.set_os_rmdir_scenario('okay')
    double.register_for_testcase(testcase)

    func_patcher = mock.patch.object(tempfile, "mkdtemp", autospec=True)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)

    tempfile.mkdtemp.return_value = testcase.tempfile_mkdtemp_file_double.path


try:
    FileNotFoundError
    FileExistsError
    PermissionError
except NameError:
    # Python 2 uses IOError.
    def _ensure_ioerror_args(init_args, init_kwargs, errno_value):
        result_kwargs = init_kwargs
        result_errno = errno_value
        result_strerror = os.strerror(errno_value)
        result_filename = None
        if len(init_args) >= 3:
            result_errno = init_args[0]
            result_filename = init_args[2]
        if 'errno' in init_kwargs:
            result_errno = init_kwargs['errno']
            del result_kwargs['errno']
        if 'filename' in init_kwargs:
            result_filename = init_kwargs['filename']
            del result_kwargs['filename']
        if len(init_args) >= 2:
            result_strerror = init_args[1]
        if 'strerror' in init_kwargs:
            result_strerror = init_kwargs['strerror']
            del result_kwargs['strerror']
        result_args = (result_errno, result_strerror, result_filename)
        return (result_args, result_kwargs)

    class FileNotFoundError(IOError):
        def __init__(self, *args, **kwargs):
            (args, kwargs) = _ensure_ioerror_args(
                    args, kwargs, errno_value=errno.ENOENT)
            super(FileNotFoundError, self).__init__(*args, **kwargs)

    class FileExistsError(IOError):
        def __init__(self, *args, **kwargs):
            (args, kwargs) = _ensure_ioerror_args(
                    args, kwargs, errno_value=errno.EEXIST)
            super(FileExistsError, self).__init__(*args, **kwargs)

    class PermissionError(IOError):
        def __init__(self, *args, **kwargs):
            (args, kwargs) = _ensure_ioerror_args(
                    args, kwargs, errno_value=errno.EPERM)
            super(PermissionError, self).__init__(*args, **kwargs)


def make_fake_file_scenarios(path=None):
    """ Make a collection of scenarios for testing with fake files.

        :path: The filesystem path of the fake file. If not specified,
            a valid random path will be generated.
        :return: A collection of scenarios for tests involving input files.

        The collection is a mapping from scenario name to a dictionary of
        scenario attributes.

        """

    if path is None:
        file_path = tempfile.mktemp()
    else:
        file_path = path

    fake_file_empty = StringIO()
    fake_file_minimal = StringIO("Lorem ipsum.")
    fake_file_large = StringIO("\n".join(
            "ABCDEFGH" * 100
            for __ in range(1000)))

    default_scenario_params = {
            'open_scenario_name': 'okay',
            'file_double_params': dict(
                path=file_path, fake_file=fake_file_minimal),
            }

    scenarios = {
            'default': {},
            'error-not-exist': {
                'open_scenario_name': 'nonexist',
                },
            'error-exist': {
                'open_scenario_name': 'exist_error',
                },
            'error-read-denied': {
                'open_scenario_name': 'read_denied',
                },
            'not-found': {
                'file_double_params': dict(
                    path=file_path, fake_file=fake_file_empty),
                },
            'exist-empty': {
                'file_double_params': dict(
                    path=file_path, fake_file=fake_file_empty),
                },
            'exist-minimal': {
                'file_double_params': dict(
                    path=file_path, fake_file=fake_file_minimal),
                },
            'exist-large': {
                'file_double_params': dict(
                    path=file_path, fake_file=fake_file_large),
                },
            }

    for (name, scenario) in scenarios.items():
        params = default_scenario_params.copy()
        params.update(scenario)
        scenario.update(params)
        scenario['file_double'] = FileDouble(**scenario['file_double_params'])
        scenario['file_double'].set_open_scenario(params['open_scenario_name'])
        scenario['fake_file_scenario_name'] = name

    return scenarios


def get_file_doubles_from_fake_file_scenarios(scenarios):
    """ Get the `FileDouble` instances from fake file scenarios.

        :param scenarios: Collection of fake file scenarios.
        :return: Collection of `FileDouble` instances.

        """
    doubles = set(
            scenario['file_double']
            for scenario in scenarios
            if scenario['file_double'] is not None)

    return doubles


def setup_file_double_behaviour(testcase, doubles=None):
    """ Set up file double instances and behaviour.

        :param testcase: The `TestCase` instance to modify.
        :param doubles: Collection of `FileDouble` instances.
        :return: None.

        If `doubles` is ``None``, a default collection will be made
        from the result of `make_fake_file_scenarios` result.

        """
    if doubles is None:
        scenarios = make_fake_file_scenarios()
        doubles = get_file_doubles_from_fake_file_scenarios(
                scenarios.values())

    for file_double in doubles:
        file_double.register_for_testcase(testcase)

    orig_open = builtins.open

    def fake_open(path, mode='rt', buffering=-1):
        registry = FileDouble.get_registry_for_testcase(testcase)
        if path in registry:
            file_double = registry[path]
            result = file_double.builtins_open_scenario.call_hook(
                    mode, buffering)
        else:
            result = orig_open(path, mode, buffering)
        return result

    mock_open = mock.mock_open()
    mock_open.side_effect = fake_open

    func_patcher = mock.patch.object(
            builtins, "open", new=mock_open)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def setup_fake_file_fixtures(testcase):
    """ Set up fixtures for fake file doubles.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        """
    scenarios = make_fake_file_scenarios()
    testcase.fake_file_scenarios = scenarios

    file_doubles = get_file_doubles_from_fake_file_scenarios(
            scenarios.values())
    setup_file_double_behaviour(testcase, file_doubles)


def set_fake_file_scenario(testcase, name):
    """ Set the named fake file scenario for the test case. """
    scenario = testcase.fake_file_scenarios[name]
    testcase.fake_file_scenario = scenario
    testcase.file_double = scenario['file_double']
    testcase.file_double.register_for_testcase(testcase)


class TestDoubleFunctionScenario:
    """ Scenario for fake behaviour of a specific function. """

    def __init__(self, scenario_name, double):
        self.scenario_name = scenario_name
        self.double = double

        self.call_hook = getattr(
                self, "_hook_{name}".format(name=self.scenario_name))

    def __repr__(self):
        text = (
                "<{class_name} instance: {id}"
                " name: {name!r},"
                " call_hook name: {hook_name!r}"
                " double: {double!r}"
                ">").format(
                    class_name=self.__class__.__name__, id=id(self),
                    name=self.scenario_name, double=self.double,
                    hook_name=self.call_hook.__name__)
        return text

    def __eq__(self, other):
        result = True
        if not self.scenario_name == other.scenario_name:
            result = False
        if not self.double == other.double:
            result = False
        if not self.call_hook.__name__ == other.call_hook.__name__:
            result = False
        return result

    def __ne__(self, other):
        result = not self.__eq__(other)
        return result


class os_path_exists_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.path.exists` behaviour. """

    def _hook_exist(self):
        return True

    def _hook_not_exist(self):
        return False


class os_access_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.access` behaviour. """

    def _hook_okay(self, mode):
        return True

    def _hook_not_exist(self, mode):
        return False

    def _hook_read_only(self, mode):
        if mode & (os.W_OK | os.X_OK):
            result = False
        else:
            result = True
        return result

    def _hook_denied(self, mode):
        if mode & (os.R_OK | os.W_OK | os.X_OK):
            result = False
        else:
            result = True
        return result


class os_stat_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.stat` behaviour. """

    def _hook_okay(self):
        return self.double.stat_result

    def _hook_notfound_error(self):
        raise FileNotFoundError(
                self.double.path,
                "No such file or directory: {path!r}".format(
                    path=self.double.path))

    def _hook_denied_error(self):
        raise PermissionError(
                self.double.path,
                "Permission denied")


class os_lstat_scenario(os_stat_scenario):
    """ Scenario for `os.lstat` behaviour. """


class os_unlink_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.unlink` behaviour. """

    def _hook_okay(self):
        return None

    def _hook_nonexist(self):
        error = FileNotFoundError(
                self.double.path,
                "No such file or directory: {path!r}".format(
                    path=self.double.path))
        raise error

    def _hook_denied(self):
        error = PermissionError(
                self.double.path,
                "Permission denied")
        raise error


class os_rmdir_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.rmdir` behaviour. """

    def _hook_okay(self):
        return None

    def _hook_nonexist(self):
        error = FileNotFoundError(
                self.double.path,
                "No such file or directory: {path!r}".format(
                    path=self.double.path))
        raise error

    def _hook_denied(self):
        error = PermissionError(
                self.double.path,
                "Permission denied")
        raise error


class shutil_rmtree_scenario(TestDoubleFunctionScenario):
    """ Scenario for `shutil.rmtree` behaviour. """

    def _hook_okay(self):
        return None

    def _hook_nonexist(self):
        error = FileNotFoundError(
                self.double.path,
                "No such file or directory: {path!r}".format(
                    path=self.double.path))
        raise error

    def _hook_denied(self):
        error = PermissionError(
                self.double.path,
                "Permission denied")
        raise error


class builtins_open_scenario(TestDoubleFunctionScenario):
    """ Scenario for `builtins.open` behaviour. """

    def _hook_okay(self, mode, buffering):
        result = self.double.fake_file
        return result

    def _hook_nonexist(self, mode, buffering):
        if mode.startswith('r'):
            error = FileNotFoundError(
                    self.double.path,
                    "No such file or directory: {path!r}".format(
                        path=self.double.path))
            raise error
        result = self.double.fake_file
        return result

    def _hook_exist_error(self, mode, buffering):
        if mode.startswith('w') or mode.startswith('a'):
            error = FileExistsError(
                    self.double.path,
                    "File already exists: {path!r}".format(
                        path=self.double.path))
            raise error
        result = self.double.fake_file
        return result

    def _hook_read_denied(self, mode, buffering):
        if mode.startswith('r'):
            error = PermissionError(
                    self.double.path,
                    "Read denied on {path!r}".format(
                        path=self.double.path))
            raise error
        result = self.double.fake_file
        return result

    def _hook_write_denied(self, mode, buffering):
        if mode.startswith('w') or mode.startswith('a'):
            error = PermissionError(
                    self.double.path,
                    "Write denied on {path!r}".format(
                        path=self.double.path))
            raise error
        result = self.double.fake_file
        return result


class TestDoubleWithRegistry:
    """ Abstract base class for a test double with a test case registry. """

    registry_class = NotImplemented
    registries = NotImplemented

    function_scenario_params_by_class = NotImplemented

    def __new__(cls, *args, **kwargs):
        superclass = super(TestDoubleWithRegistry, cls)
        if superclass.__new__ is object.__new__:
            # The ‘object’ implementation complains about extra arguments.
            instance = superclass.__new__(cls)
        else:
            instance = superclass.__new__(cls, *args, **kwargs)
        instance.make_set_scenario_methods()

        return instance

    def __init__(self, *args, **kwargs):
        super(TestDoubleWithRegistry, self).__init__(*args, **kwargs)
        self._set_method_per_scenario()

    def _make_set_scenario_method(self, scenario_class, params):
        def method(self, name):
            scenario = scenario_class(name, double=self)
            setattr(self, scenario_class.__name__, scenario)
        method.__doc__ = (
                """ Set the scenario for `{name}` behaviour. """
                ).format(name=scenario_class.__name__)
        method.__name__ = str(params['set_scenario_method_name'])
        return method

    def make_set_scenario_methods(self):
        """ Make `set_<scenario_class_name>` methods on this class. """
        for (function_scenario_class, function_scenario_params) in (
                self.function_scenario_params_by_class.items()):
            method = self._make_set_scenario_method(
                    function_scenario_class, function_scenario_params)
            setattr(self.__class__, method.__name__, method)
            function_scenario_params['set_scenario_method'] = method

    def _set_method_per_scenario(self):
        """ Set the method to be called for each scenario. """
        for function_scenario_params in (
                self.function_scenario_params_by_class.values()):
            function_scenario_params['set_scenario_method'](
                    self, function_scenario_params['default_scenario_name'])

    @classmethod
    def get_registry_for_testcase(cls, testcase):
        """ Get the FileDouble registry for the specified test case. """
        # Key in a dict must be hashable.
        key = (testcase.__class__, id(testcase))
        registry = cls.registries.setdefault(key, cls.registry_class())
        return registry

    def get_registry_key(self):
        """ Get the registry key for this double. """
        raise NotImplementedError

    def register_for_testcase(self, testcase):
        """ Add this instance to registry for the specified testcase. """
        registry = self.get_registry_for_testcase(testcase)
        key = self.get_registry_key()
        registry[key] = self
        unregister_func = functools.partial(
                self.unregister_for_testcase, testcase)
        testcase.addCleanup(unregister_func)

    def unregister_for_testcase(self, testcase):
        """ Remove this instance from registry for the specified testcase. """
        registry = self.get_registry_for_testcase(testcase)
        key = self.get_registry_key()
        if key in registry:
            registry.pop(key)


def copy_fake_file(fake_file):
    """ Make a copy of the StringIO instance. """
    fake_file_type = StringIO
    content = ""
    if fake_file is not None:
        fake_file_type = type(fake_file)
        content = fake_file.getvalue()
    assert issubclass(fake_file_type, object)
    result = fake_file_type(content)
    if hasattr(fake_file, 'encoding'):
        if not hasattr(result, 'encoding'):
            result.encoding = fake_file.encoding
    return result


class FileDouble(TestDoubleWithRegistry):
    """ A testing double for a file. """

    registry_class = dict
    registries = {}

    function_scenario_params_by_class = {
            os_path_exists_scenario: {
                'default_scenario_name': 'not_exist',
                'set_scenario_method_name': 'set_os_path_exists_scenario',
                },
            os_access_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_os_access_scenario',
                },
            os_stat_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_os_stat_scenario',
                },
            os_lstat_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_os_lstat_scenario',
                },
            builtins_open_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_open_scenario',
                },
            os_unlink_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_os_unlink_scenario',
                },
            os_rmdir_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_os_rmdir_scenario',
                },
            shutil_rmtree_scenario: {
                'default_scenario_name': 'okay',
                'set_scenario_method_name': 'set_shutil_rmtree_scenario',
                },
            }

    def __init__(self, path=None, fake_file=None, *args, **kwargs):
        self.path = path
        self.fake_file = copy_fake_file(fake_file)
        self.fake_file.name = path

        self._set_stat_result()

        super(FileDouble, self).__init__(*args, **kwargs)

    def _set_stat_result(self):
        """ Set the `os.stat` result for this file. """
        size = len(self.fake_file.getvalue())
        self.stat_result = StatResult(
                st_mode=0,
                st_ino=None, st_dev=None, st_nlink=None,
                st_uid=0, st_gid=0,
                st_size=size,
                st_atime=None, st_mtime=None, st_ctime=None,
                )

    def __repr__(self):
        text = "FileDouble(path={path!r}, fake_file={fake_file!r})".format(
                path=self.path, fake_file=self.fake_file)
        return text

    def get_registry_key(self):
        """ Get the registry key for this double. """
        result = self.path
        return result


class os_popen_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.popen` behaviour. """

    stream_name_by_mode = {
            'w': 'stdin',
            'r': 'stdout',
            }

    def _hook_success(self, argv, mode, buffering):
        stream_name = self.stream_name_by_mode[mode]
        stream_double = getattr(
                self.double, stream_name + '_double')
        result = stream_double.fake_file
        return result

    def _hook_failure(self, argv, mode, buffering):
        result = StringIO()
        return result

    def _hook_not_found(self, argv, mode, buffering):
        result = StringIO()
        return result


class os_waitpid_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.waitpid` behaviour. """

    def _hook_success(self, pid, options):
        result = (pid, EXIT_STATUS_SUCCESS)
        return result

    def _hook_failure(self, pid, options):
        result = (pid, EXIT_STATUS_FAILURE)
        return result

    def _hook_not_found(self, pid, options):
        error = OSError(errno.ECHILD)
        raise error


class os_system_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.system` behaviour. """

    def _hook_success(self, command):
        result = EXIT_STATUS_SUCCESS
        return result

    def _hook_failure(self, command):
        result = EXIT_STATUS_FAILURE
        return result

    def _hook_not_found(self, command):
        result = EXIT_STATUS_COMMAND_NOT_FOUND
        return result


class os_spawnv_scenario(TestDoubleFunctionScenario):
    """ Scenario for `os.spawnv` behaviour. """

    def _hook_success(self, mode, file, args):
        result = EXIT_STATUS_SUCCESS
        return result

    def _hook_failure(self, mode, file, args):
        result = EXIT_STATUS_FAILURE
        return result

    def _hook_not_found(self, mode, file, args):
        result = EXIT_STATUS_COMMAND_NOT_FOUND
        return result


ARG_ANY = object()
ARG_MORE = object()


class PopenDouble:
    """ A testing double for `subprocess.Popen`. """

    def __init__(self, args, *posargs, **kwargs):
        self.stdin = None
        self.stdout = None
        self.stderr = None
        self.pid = None
        self.returncode = None

        if kwargs.get('shell', False):
            self.argv = shlex.split(args)
        else:
            # The paramter is already a sequence of command-line arguments.
            self.argv = args

    def set_streams(self, subprocess_double, popen_kwargs):
        """ Set the streams on the `PopenDouble`.

            :param subprocess_double: The `SubprocessDouble` from
                which to get existing stream doubles.
            :param popen_kwargs: The keyword arguments to the
                `subprocess.Popen` call.
            :return: ``None``.

            """
        for stream_name in (
                name for name in ['stdin', 'stdout', 'stderr']
                if name in popen_kwargs):
            stream_spec = popen_kwargs[stream_name]
            if stream_spec is subprocess.PIPE:
                stream_double = getattr(
                        subprocess_double,
                        "{name}_double".format(name=stream_name))
                stream_file = stream_double.fake_file
            elif stream_spec is subprocess.STDOUT:
                stream_file = subprocess_double.stdout_double.fake_file
            else:
                stream_file = stream_spec
            setattr(self, stream_name, stream_file)

    def wait(self):
        """ Wait for subprocess to terminate. """
        return self.returncode


class subprocess_popen_scenario(TestDoubleFunctionScenario):
    """ Scenario for `subprocess.Popen` behaviour. """

    def _hook_success(self, testcase, args, *posargs, **kwargs):
        double = self.double.popen_double
        double.set_streams(self.double, kwargs)
        return double


def patch_subprocess_popen(testcase):
    """ Patch `subprocess.Popen` constructor for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_subprocess_popen = subprocess.Popen

    def fake_subprocess_popen(args, *posargs, **kwargs):
        if kwargs.get('shell', False):
            argv = shlex.split(args)
        else:
            argv = args
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        if argv in registry:
            subprocess_double = registry[argv]
            result = subprocess_double.subprocess_popen_scenario.call_hook(
                    testcase, args, *posargs, **kwargs)
        else:
            result = orig_subprocess_popen(args, *posargs, **kwargs)
        return result

    func_patcher = mock.patch.object(
            subprocess, "Popen", autospec=True,
            side_effect=fake_subprocess_popen)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


class subprocess_call_scenario(TestDoubleFunctionScenario):
    """ Scenario for `subprocess.call` behaviour. """

    def _hook_success(self, command):
        result = EXIT_STATUS_SUCCESS
        return result

    def _hook_failure(self, command):
        result = EXIT_STATUS_FAILURE
        return result

    def _hook_not_found(self, command):
        result = EXIT_STATUS_COMMAND_NOT_FOUND
        return result


def patch_subprocess_call(testcase):
    """ Patch `subprocess.call` function for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_subprocess_call = subprocess.call

    def fake_subprocess_call(command, *posargs, **kwargs):
        if kwargs.get('shell', False):
            command_argv = shlex.split(command)
        else:
            command_argv = command
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        if command_argv in registry:
            subprocess_double = registry[command_argv]
            result = subprocess_double.subprocess_call_scenario.call_hook(
                    command)
        else:
            result = orig_subprocess_call(command, *posargs, **kwargs)
        return result

    func_patcher = mock.patch.object(
            subprocess, "call", autospec=True,
            side_effect=fake_subprocess_call)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


class subprocess_check_call_scenario(TestDoubleFunctionScenario):
    """ Scenario for `subprocess.check_call` behaviour. """

    def _hook_success(self, command):
        return None

    def _hook_failure(self, command):
        result = EXIT_STATUS_FAILURE
        error = subprocess.CalledProcessError(result, command)
        raise error

    def _hook_not_found(self, command):
        result = EXIT_STATUS_COMMAND_NOT_FOUND
        error = subprocess.CalledProcessError(result, command)
        raise error


def patch_subprocess_check_call(testcase):
    """ Patch `subprocess.check_call` function for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_subprocess_check_call = subprocess.check_call

    def fake_subprocess_check_call(command, *posargs, **kwargs):
        if kwargs.get('shell', False):
            command_argv = shlex.split(command)
        else:
            command_argv = command
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        if command_argv in registry:
            subprocess_double = registry[command_argv]
            scenario = subprocess_double.subprocess_check_call_scenario
            result = scenario.call_hook(command)
        else:
            result = orig_subprocess_check_call(command, *posargs, **kwargs)
        return result

    func_patcher = mock.patch.object(
            subprocess, "check_call", autospec=True,
            side_effect=fake_subprocess_check_call)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


class SubprocessDoubleRegistry(collections_abc.MutableMapping):
    """ Registry of `SubprocessDouble` instances by `argv`. """

    def __init__(self, *args, **kwargs):
        items = []
        if args:
            if isinstance(args[0], collections_abc.Mapping):
                items = args[0].items()
            if isinstance(args[0], collections_abc.Iterable):
                items = args[0]
        self._mapping = dict(items)

    def __repr__(self):
        text = "<{class_name} object: {mapping}>".format(
                class_name=self.__class__.__name__, mapping=self._mapping)
        return text

    def _match_argv(self, argv):
        """ Match the specified `argv` with our registered keys. """
        match = None
        if not isinstance(argv, collections_abc.Sequence):
            return match
        candidates = iter(self._mapping)
        while match is None:
            try:
                candidate = next(candidates)
            except StopIteration:
                break
            found = None
            if candidate == argv:
                # An exact match.
                found = True
            word_iter = enumerate(candidate)
            while found is None:
                try:
                    (word_index, candidate_word) = next(word_iter)
                except StopIteration:
                    break
                if candidate_word is ARG_MORE:
                    # Candiate matches any remaining words. We have a match.
                    found = True
                elif word_index > len(argv):
                    # Candidate is too long for the specified argv.
                    found = False
                elif candidate_word is ARG_ANY:
                    # Candidate matches any word at this position.
                    continue
                elif candidate_word == argv[word_index]:
                    # Candidate matches the word at this position.
                    continue
                else:
                    # This candidate does not match.
                    found = False
            if found is None:
                # Reached the end of the candidate without a mismatch.
                found = True
            if found:
                match = candidate
        return match

    def __getitem__(self, key):
        match = self._match_argv(key)
        if match is None:
            raise KeyError(key)
        result = self._mapping[match]
        return result

    def __setitem__(self, key, value):
        if key in self:
            del self[key]
        self._mapping[key] = value

    def __delitem__(self, key):
        match = self._match_argv(key)
        if match is not None:
            del self._mapping[match]

    def __iter__(self):
        return self._mapping.__iter__()

    def __len__(self):
        return self._mapping.__len__()


class SubprocessDouble(TestDoubleWithRegistry):
    """ A testing double for a subprocess. """

    registry_class = SubprocessDoubleRegistry
    registries = {}

    double_by_pid = weakref.WeakValueDictionary()

    function_scenario_params_by_class = {
            subprocess_popen_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_subprocess_popen_scenario',
                },
            subprocess_call_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_subprocess_call_scenario',
                },
            subprocess_check_call_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name':
                    'set_subprocess_check_call_scenario',
                },
            os_popen_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_os_popen_scenario',
                },
            os_waitpid_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_os_waitpid_scenario',
                },
            os_system_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_os_system_scenario',
                },
            os_spawnv_scenario: {
                'default_scenario_name': 'success',
                'set_scenario_method_name': 'set_os_spawnv_scenario',
                },
            }

    def __init__(self, path=None, argv=None, *args, **kwargs):
        if path is None:
            path = tempfile.mktemp()
        self.path = path

        if argv is None:
            command_name = os.path.basename(path)
            argv = [command_name]
        self.argv = argv

        self.pid = self._make_pid()
        self._register_by_pid()

        self.set_popen_double()

        stream_class = SubprocessDouble.stream_class
        for stream_name in ['stdin', 'stdout', 'stderr']:
            fake_file = stream_class()
            file_double = FileDouble(fake_file=fake_file)
            stream_double_name = '{name}_double'.format(name=stream_name)
            setattr(self, stream_double_name, file_double)

        super(SubprocessDouble, self).__init__(*args, **kwargs)

    def set_popen_double(self):
        """ Set the `PopenDouble` for this instance. """
        double = PopenDouble(self.argv)
        double.pid = self.pid

        self.popen_double = double

    def __repr__(self):
        text = (
                "<SubprocessDouble instance: {id}"
                " path: {path!r},"
                " argv: {argv!r}"
                " stdin_double: {stdin_double!r}"
                " stdout_double: {stdout_double!r}"
                " stderr_double: {stderr_double!r}"
                ">").format(
                    id=id(self),
                    path=self.path, argv=self.argv,
                    stdin_double=self.stdin_double,
                    stdout_double=self.stdout_double,
                    stderr_double=self.stderr_double)
        return text

    @classmethod
    def _make_pid(cls):
        """ Make a unique PID for a subprocess. """
        for pid in itertools.count(1):
            yield pid

    def _register_by_pid(self):
        """ Register this subprocess by its PID. """
        self.__class__.double_by_pid[self.pid] = self

    def get_registry_key(self):
        """ Get the registry key for this double. """
        result = tuple(self.argv)
        return result

    stream_class = io.BytesIO
    stream_encoding = "utf-8"

    def set_stdin_content(self, text, bytes_encoding=stream_encoding):
        """ Set the content of the `stdin` stream for this double. """
        content = text.encode(bytes_encoding)
        fake_file = self.stream_class(content)
        self.stdin_double.fake_file = fake_file

    def set_stdout_content(self, text, bytes_encoding=stream_encoding):
        """ Set the content of the `stdout` stream for this double. """
        content = text.encode(bytes_encoding)
        fake_file = self.stream_class(content)
        self.stdout_double.fake_file = fake_file

    def set_stderr_content(self, text, bytes_encoding=stream_encoding):
        """ Set the content of the `stderr` stream for this double. """
        content = text.encode(bytes_encoding)
        fake_file = self.stream_class(content)
        self.stderr_double.fake_file = fake_file


def make_fake_subprocess_scenarios(path=None):
    """ Make a collection of scenarios for testing with fake files.

        :path: The filesystem path of the fake program. If not specified,
            a valid random path will be generated.
        :return: A collection of scenarios for tests involving subprocesses.

        The collection is a mapping from scenario name to a dictionary of
        scenario attributes.

        """
    if path is None:
        file_path = tempfile.mktemp()
    else:
        file_path = path

    default_scenario_params = {
            'return_value': EXIT_STATUS_SUCCESS,
            'program_path': file_path,
            'argv_after_command_name': [],
            }

    scenarios = {
            'default': {},
            'not-found': {
                'return_value': EXIT_STATUS_COMMAND_NOT_FOUND,
                },
            }

    for (name, scenario) in scenarios.items():
        params = default_scenario_params.copy()
        params.update(scenario)
        scenario.update(params)
        program_path = params['program_path']
        program_name = os.path.basename(params['program_path'])
        argv = [program_name]
        argv.extend(params['argv_after_command_name'])
        subprocess_double_params = dict(
                path=program_path,
                argv=argv,
                )
        subprocess_double = SubprocessDouble(**subprocess_double_params)
        scenario['subprocess_double'] = subprocess_double
        scenario['fake_file_scenario_name'] = name

    return scenarios


def get_subprocess_doubles_from_fake_subprocess_scenarios(scenarios):
    """ Get the `SubprocessDouble` instances from fake subprocess scenarios.

        :param scenarios: Collection of fake subprocess scenarios.
        :return: Collection of `SubprocessDouble` instances.

        """
    doubles = set(
            scenario['subprocess_double']
            for scenario in scenarios
            if scenario['subprocess_double'] is not None)

    return doubles


def setup_subprocess_double_behaviour(testcase, doubles=None):
    """ Set up subprocess double instances and behaviour.

        :param testcase: The `TestCase` instance to modify.
        :param doubles: Collection of `SubprocessDouble` instances.
        :return: None.

        If `doubles` is ``None``, a default collection will be made
        from the return value of `make_fake_subprocess_scenarios`.

        """
    if doubles is None:
        scenarios = make_fake_subprocess_scenarios()
        doubles = get_subprocess_doubles_from_fake_subprocess_scenarios(
                scenarios.values())

    for double in doubles:
        double.register_for_testcase(testcase)


def setup_fake_subprocess_fixtures(testcase):
    """ Set up fixtures for fake subprocess doubles.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        """
    scenarios = make_fake_subprocess_scenarios()
    testcase.fake_subprocess_scenarios = scenarios

    doubles = get_subprocess_doubles_from_fake_subprocess_scenarios(
            scenarios.values())
    setup_subprocess_double_behaviour(testcase, doubles)


def patch_os_popen(testcase):
    """ Patch `os.popen` behaviour for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_os_popen = os.popen

    def fake_os_popen(cmd, mode='r', buffering=-1):
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        if isinstance(cmd, basestring):
            command_argv = shlex.split(cmd)
        else:
            command_argv = cmd
        if command_argv in registry:
            subprocess_double = registry[command_argv]
            result = subprocess_double.os_popen_scenario.call_hook(
                    command_argv, mode, buffering)
        else:
            result = orig_os_popen(cmd, mode, buffering)
        return result

    func_patcher = mock.patch.object(
            os, "popen", autospec=True,
            side_effect=fake_os_popen)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_waitpid(testcase):
    """ Patch `os.waitpid` behaviour for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_os_waitpid = os.waitpid

    def fake_os_waitpid(pid, options):
        registry = SubprocessDouble.double_by_pid
        if pid in registry:
            subprocess_double = registry[pid]
            result = subprocess_double.os_waitpid_scenario.call_hook(
                    pid, options)
        else:
            result = orig_os_waitpid(pid, options)
        return result

    func_patcher = mock.patch.object(
            os, "waitpid", autospec=True,
            side_effect=fake_os_waitpid)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_system(testcase):
    """ Patch `os.system` behaviour for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_os_system = os.system

    def fake_os_system(command):
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        command_argv = shlex.split(command)
        if command_argv in registry:
            subprocess_double = registry[command_argv]
            result = subprocess_double.os_system_scenario.call_hook(
                    command)
        else:
            result = orig_os_system(command)
        return result

    func_patcher = mock.patch.object(
            os, "system", autospec=True,
            side_effect=fake_os_system)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


def patch_os_spawnv(testcase):
    """ Patch `os.spawnv` behaviour for this test case.

        :param testcase: The `TestCase` instance to modify.
        :return: None.

        When the patched function is called, the registry of
        `SubprocessDouble` instances for this test case will be used
        to get the instance for the program path specified.

        """
    orig_os_spawnv = os.spawnv

    def fake_os_spawnv(mode, file, args):
        registry = SubprocessDouble.get_registry_for_testcase(testcase)
        registry_key = tuple(args)
        if registry_key in registry:
            subprocess_double = registry[registry_key]
            result = subprocess_double.os_spawnv_scenario.call_hook(
                    mode, file, args)
        else:
            result = orig_os_spawnv(mode, file, args)
        return result

    func_patcher = mock.patch.object(
            os, "spawnv", autospec=True,
            side_effect=fake_os_spawnv)
    func_patcher.start()
    testcase.addCleanup(func_patcher.stop)


# Copyright © 2015–2016 Ben Finney <bignose@debian.org>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 3 of that license or any later version.
# No warranty expressed or implied. See the file ‘LICENSE.GPL-3’ for details.


# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :