File: auto.py

package info (click to toggle)
python-distutils-extra 3.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 220 kB
  • sloc: python: 1,817; makefile: 10
file content (1277 lines) | stat: -rwxr-xr-x 40,897 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
#!/usr/bin/python3

"""Test DistUtilsExtra.auto."""

# TODO: Address following pylint complaints
# pylint: disable=consider-using-with,invalid-name,too-many-lines,use-a-generator

import os
import pathlib
import re
import shutil
import subprocess
import tempfile
import unittest


# pylint: disable-next=too-many-public-methods
class T(unittest.TestCase):
    """Test DistUtilsExtra.auto."""

    def setUp(self):
        self.maxDiff = None
        self.src = tempfile.mkdtemp()

        self._mksrc(
            "setup.py",
            """
# ignore warning about import from local path
import warnings
warnings.filterwarnings('ignore', 'Module DistUtilsExtra was already imported from.*')
warnings.filterwarnings('ignore', 'pipe2 set errno ENOSYS.*')
warnings.filterwarnings('ignore', 'setup.py install is deprecated.*')

from DistUtilsExtra.auto import setup

setup(
    name='foo',
    version='0.1',
    description='Test suite package',
    url='https://foo.example.com',
    license='GPL v2 or later',
    author='Martin Pitt',
    author_email='martin.pitt@example.com',
)
""",
        )
        self.snapshot = None
        self.install_tree = None

    def tearDown(self):
        try:
            # check that setup.py clean removes everything
            (o, e, s) = self.setup_py(["clean", "-a"])
            self.assertEqual(s, 0, o + e)
            cruft = self.diff_snapshot()
            self.assertEqual(cruft, "", f"no cruft after cleaning:\n{cruft}")
        finally:
            shutil.rmtree(self.src)
            if self.snapshot:
                shutil.rmtree(self.snapshot)
            if self.install_tree:
                shutil.rmtree(self.install_tree)
            self.src = None
            self.snapshot = None
            self.install_tree = None

    def assert_egg_info_directory_is_present_and_well(self):
        """Check that no .egg-info file is present, that an egg_info directory
        is present and that it contains the expected files"""

        f = self.installed_files()
        # All files are in an .egg-info directory; no .egg-info file is created
        self.assertFalse(any([_.endswith(".egg-info") for _ in f]))
        # There are 4 files in said directory
        self.assertEqual(len(f), 4)
        # Check that the four exist
        self.assertTrue(
            all(
                [
                    any(
                        [
                            _.endswith(c)
                            for c in [
                                "PKG-INFO",
                                "SOURCES.txt",
                                "dependency_links.txt",
                                "top_level.txt",
                            ]
                        ]
                    )
                    for _ in f
                ]
            )
        )

    #
    # actual tests come here
    #

    def test_empty(self):
        """empty source tree (just setup.py)"""

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        self.assert_egg_info_directory_is_present_and_well()

    def test_vcs(self):
        """Ignores revision control files"""

        self._mksrc(".shelf/1")
        self._mksrc(".bzr/revs")
        self._mksrc(".git/config")
        self._mksrc(".svn/revs")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        self.assert_egg_info_directory_is_present_and_well()

    def test_modules(self):
        """Python modules"""

        self._mksrc("yesme.py", b'x ="a\xc3\xa4b\xe2\x99\xa5"'.decode("UTF-8"))
        self._mksrc("stuff/notme.py", b'x ="a\xc3\xa4b\xe2\x99\xa5"'.decode("UTF-8"))
        self._mksrc(
            "stuff/withencoding.py",
            b"# -*- Mode: Python; coding: utf-8; -*- \nfoo = 1".decode("UTF-8"),
        )

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  stuff/notme.py\n", o)

        f = "\n".join(self.installed_files())
        self.assertIn("-packages/yesme.py", f)
        self.assertNotIn("notme", f)

    def test_packages(self):
        """Python packages"""

        self._mksrc("foopkg/__init__.py", "")
        self._mksrc("foopkg/bar.py")
        self._mksrc("foopkg/baz.py")
        self._mksrc("noinit/notme.py")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  noinit/notme.py\n", o)

        f = "\n".join(self.installed_files())
        self.assertIn("foopkg/__init__.py", f)
        self.assertIn("foopkg/bar.py", f)
        self.assertNotIn("noinit", f)

    def test_dbus(self):
        """D-BUS configuration and service files"""

        # D-BUS ACL configuration file
        self._mksrc(
            "daemon/com.example.foo.conf",
            """<!DOCTYPE busconfig PUBLIC
 "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
</busconfig>""",
        )

        # non-D-BUS configuration file
        self._mksrc("daemon/defaults.conf", "start = True\nlog = syslog")

        # D-BUS system service
        self._mksrc(
            "daemon/com.example.foo.service",
            """[D-BUS Service]
Name=com.example.Foo
Exec=/usr/lib/foo/foo_daemon
User=root""",
        )

        # D-BUS session service
        self._mksrc(
            "gui/com.example.foo.gui.service",
            """[D-BUS Service]
Name=com.example.Foo.GUI
Exec=/usr/bin/foo-gtk
""",
        )

        # non-D-BUS .service file
        self._mksrc("stuff/super.service", "I am a file")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  stuff/super.service\n", o)

        f = self.installed_files()
        self.assertEqual(len(f), 7)  # 3 D-BUS files plus 4 files in egg-info directory
        self.assertIn("/etc/dbus-1/system.d/com.example.foo.conf", f)
        self.assertIn("/usr/share/dbus-1/system-services/com.example.foo.service", f)
        self.assertIn("/usr/share/dbus-1/services/com.example.foo.gui.service", f)
        self.assertNotIn("super.service", "\n".join(f))

    def test_gsettings(self):
        """GSettings schema files"""

        # schema files in dedicated directory
        self._mksrc("data/glib-2.0/schemas/org.test.myapp.gschema.xml")
        self._mksrc("data/glib-2.0/schemas/gschemas.compiled")
        # schema files in data directory
        self._mksrc("data/org.test.myapp2.gschema.xml")
        self._mksrc("data/gschemas.compiled")

        (_, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)

        f = self.installed_files()
        self.assertEqual(
            len(f), 6
        )  # 2 schema files plus 4 files in .egg-info directory
        self.assertIn("/usr/share/glib-2.0/schemas/org.test.myapp.gschema.xml", f)
        self.assertNotIn("gschemas.compiled", "\n".join(f))

    def test_apport_hook(self):
        """Apport hooks"""

        self._mksrc(
            "apport/foo.py",
            """import os
def add_info(report):
    pass
""",
        )

        self._mksrc(
            "apport/source_foo.py",
            """import os
def add_info(report):
    pass
""",
        )

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertEqual(len(f), 6, f)  # 2 hook files plus 4 in .egg-info
        self.assertIn("/usr/share/apport/package-hooks/foo.py", f)
        self.assertIn("/usr/share/apport/package-hooks/source_foo.py", f)

    def test_po(self):
        """gettext *.po files"""

        self._mkpo()

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)
        f = self.installed_files()
        self.assertIn("/usr/share/locale/de/LC_MESSAGES/foo.mo", f)
        self.assertIn("/usr/share/locale/fr/LC_MESSAGES/foo.mo", f)
        self.assertNotIn("junk", "\n".join(f))

        msgunfmt = subprocess.Popen(
            [
                "msgunfmt",
                os.path.join(
                    self.install_tree, "usr/share/locale/de/LC_MESSAGES/foo.mo"
                ),
            ],
            stdout=subprocess.PIPE,
        )
        out = msgunfmt.communicate()[0].decode()
        self.assertEqual(out, self._src_contents("po/de.po"))

    def test_policykit(self):
        """*.policy.in PolicyKit files"""

        self._mksrc(
            "daemon/com.example.foo.policy.in",
            """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
 "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
  <vendor>Foo project</vendor>
  <vendor_url>https://foo.example.com</vendor_url>

  <action id="com.example.foo.greet">
    <_description>Good morning</_description>
    <_message>Hello</_message>
    <defaults>
      <allow_active>yes</allow_active>
    </defaults>
  </action>
</policyconfig>""",
        )

        self._mkpo()
        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/usr/share/polkit-1/actions/com.example.foo.policy", f)
        p = self._installed_contents(
            "usr/share/polkit-1/actions/com.example.foo.policy"
        )
        self.assertIn("<description>Good morning</description>", p)
        self.assertIn('<description xml:lang="de">Guten Morgen</description>', p)
        self.assertIn("<message>Hello</message>", p)
        self.assertIn('<message xml:lang="de">Hallo</message>', p)

    def test_desktop(self):
        """*.desktop.in files"""

        self._mksrc(
            "gui/foogtk.desktop.in",
            """[Desktop Entry]
_Name=Hello
_Comment=Good morning
Exec=/bin/foo""",
        )
        self._mksrc(
            "gui/autostart/fooapplet.desktop.in",
            """[Desktop Entry]
_Name=Hello
_Comment=Good morning
Exec=/usr/bin/fooapplet""",
        )
        self._mkpo()
        self._mksrc(
            "data/foosettings.desktop.in",
            """[Desktop Entry]
_Name=Hello
_Comment=Good morning
Exec=/bin/foosettings""",
        )

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/usr/share/autostart/fooapplet.desktop", f)
        self.assertIn("/usr/share/applications/foogtk.desktop", f)
        self.assertIn("/usr/share/applications/foosettings.desktop", f)
        # data/*.desktop.in shouldn't go to data dir
        self.assertNotIn("/usr/share/foo/", f)

        p = self._installed_contents("usr/share/autostart/fooapplet.desktop")
        self.assertIn("\nName=Hello\n", p)
        self.assertIn("\nName[de]=Hallo\n", p)
        self.assertIn("\nComment[fr]=Bonjour\n", p)

    def test_icons(self):
        """data/icons/"""

        self._mksrc("data/icons/scalable/actions/press.png")
        self._mksrc("data/icons/48x48/apps/foo.png")
        scalable_icon_path = os.path.join(self.src, "data", "icons", "scalable")
        os.symlink(
            os.path.join(scalable_icon_path, "actions", "press.png"),
            os.path.join(scalable_icon_path, "actions", "crunch.png"),
        )

        # test broken symlink, too
        os.mkdir(os.path.join(scalable_icon_path, "mimetypes"))
        os.symlink(
            "../apps/foo.svg",
            os.path.join(scalable_icon_path, "mimetypes", "text-x-foo.svg"),
        )

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/usr/share/icons/hicolor/scalable/actions/press.png", f)
        self.assertIn("/usr/share/icons/hicolor/scalable/actions/crunch.png", f)
        self.assertIn("/usr/share/icons/hicolor/48x48/apps/foo.png", f)
        self.assertTrue(
            os.path.islink(
                os.path.join(
                    self.install_tree,
                    "usr/share/icons/hicolor/scalable/actions/crunch.png",
                )
            )
        )
        self.assertTrue(
            os.path.islink(
                os.path.join(
                    self.install_tree,
                    "usr/share/icons/hicolor/scalable/mimetypes/text-x-foo.svg",
                )
            )
        )

    def test_data(self):
        """Auxiliary files in data/"""

        # have some explicitly covered files, to check that they don't get
        # installed into prefix/share/foo/ again
        self._mksrc(
            "setup.py",
            """
import warnings
from DistUtilsExtra.auto import setup
from glob import glob

warnings.filterwarnings('ignore', 'setup.py install is deprecated.*')

setup(
    name='foo',
    version='0.1',
    description='Test suite package',
    url='https://foo.example.com',
    license='GPL v2 or later',
    author='Martin Pitt',
    author_email='martin.pitt@example.com',

    data_files = [
      ('/lib/udev/rules.d', ['data/40-foo.rules']),
      ('/etc/foo', glob('data/*.conf')),
    ]
)
""",
        )

        self._mksrc("data/stuff")
        self._mksrc("data/handlers/red.py", 'import sys\nprint ("RED")')
        self._mksrc("data/handlers/blue.py", 'import sys\nprint ("BLUE")')
        self._mksrc("data/40-foo.rules")
        self._mksrc("data/blob1.conf")
        self._mksrc("data/blob2.conf")
        os.symlink("stuff", os.path.join(self.src, "data", "stufflink"))

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/usr/share/foo/stuff", f)
        self.assertIn("/usr/share/foo/stufflink", f)
        self.assertTrue(
            os.path.islink(
                os.path.join(self.install_tree, "usr", "share", "foo", "stufflink")
            )
        )
        self.assertIn("/usr/share/foo/handlers/red.py", f)
        self.assertIn("/usr/share/foo/handlers/blue.py", f)
        self.assertIn("/lib/udev/rules.d/40-foo.rules", f)
        self.assertIn("/etc/foo/blob1.conf", f)
        self.assertIn("/etc/foo/blob2.conf", f)
        self.assertNotIn("/usr/share/foo/blob1.conf", f)
        self.assertNotIn("/usr/share/foo/40-foo.rules", f)

    def test_scripts(self):
        """scripts"""

        # these should get autoinstalled
        self._mksrc("bin/yell", "#!/bin/sh", True)
        self._mksrc("bin/shout", "#!/bin/sh", True)
        self._mksrc(
            "bin/foo", b"#!/usr/bin/python\n# \xc2\xa9 copyright".decode("UTF-8"), True
        )
        os.symlink("shout", os.path.join(self.src, "bin", "shoutlink"))

        # these shouldn't
        self._mksrc("daemon/food", "#!/bin/sh", True)  # not in bin/
        self._mksrc("foob", "#!/bin/sh", True)  # not named like project
        # not executable
        self._mksrc(
            "bin/whisper", b"#!/usr/bin/python\n# \xc2\xa9 copyright".decode("UTF-8")
        )

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  foob", o)
        self.assertIn("\n  bin/whisper", o)
        self.assertIn("\n  daemon/food", o)

        f = self.installed_files()
        self.assertIn("/usr/bin/yell", f)
        self.assertIn("/usr/bin/shout", f)
        self.assertIn("/usr/bin/shoutlink", f)
        self.assertTrue(
            os.path.islink(os.path.join(self.install_tree, "usr", "bin", "shoutlink"))
        )
        self.assertIn("/usr/bin/foo", f)
        ftext = "\n".join(f)
        self.assertNotIn("food", ftext)
        self.assertNotIn("foob", ftext)
        self.assertNotIn("whisper", ftext)

        # verify that they are executable
        binpath = os.path.join(self.install_tree, "usr", "bin")
        self.assertTrue(os.access(os.path.join(binpath, "yell"), os.X_OK))
        self.assertTrue(os.access(os.path.join(binpath, "shout"), os.X_OK))
        self.assertTrue(os.access(os.path.join(binpath, "foo"), os.X_OK))

    def test_pot_manual(self):
        """PO template creation with manual POTFILES.in"""

        self._mk_i18n_source()
        self._mksrc("po/foo.pot", "")
        # only do a subset here
        self._mksrc(
            "po/POTFILES.in",
            """
gtk/main.py
gui/foo.desktop.in
[type: gettext/glade]gtk/test.ui""",
        )

        (o, e, s) = self.setup_py(["build"])
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        # POT file should not be shown as not recognized
        self.assertNotIn("\n  po/foo.pot\n", o)

        pot = self._src_contents("po/foo.pot")

        self.assertNotIn('msgid "no"', pot)
        self.assertIn('msgid "yes1"', pot)
        self.assertIn('msgid "yes2 %s"', pot)
        self.assertNotIn('msgid "yes5"', pot)  # we didn't add helpers.py
        self.assertIn('msgid "yes7"', pot)  # we did include the desktop file
        self.assertNotIn('msgid "yes5"', pot)  # we didn't add helpers.py
        self.assertIn('msgid "yes11"', pot)  # we added one GTKBuilder file
        self.assertNotIn('msgid "yes12"', pot)  # ... but not the other

    def test_pot_auto(self):
        """PO template creation with automatic POTFILES.in"""

        self._mk_i18n_source()

        (o, e, s) = self.setup_py(["build"])
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        # POT file should not be shown as not recognized
        self.assertNotIn("\n  po/foo.pot\n", o)

        pot = self._src_contents("po/foo.pot")

        self.assertNotIn('msgid "no"', pot)
        for i in range(2, 15):
            self.assertTrue(
                f'msgid "yes{int(i)}' in pot or f'msgid ""\n"yes{int(i)}' in pot,
                f"yes{int(i)}",
            )
        # above loop would match yes11 to yes1 as well, so test it explicitly
        self.assertIn('msgid "yes1"', pot)

    def test_pot_auto_explicit(self):
        """PO template creation with automatic POTFILES.in and explicit scripts"""

        self._mk_i18n_source()

        # add some additional binaries here which aren't caught by default
        self._mksrc("cli/client-cli", "#!/usr/bin/python\nprint (_('yes15'))", True)
        self._mksrc("gtk/client-gtk", '#!/usr/bin/python\nprint (_("yes16"))', True)
        # this is the most tricky case: intltool doesn't consider them Python
        # files by default and thus just looks for _(""):
        self._mksrc("kde/client-kde", "#!/usr/bin/python\nprint (_('yes17'))", True)
        self._mksrc("po/POTFILES.in.in", "gtk/client-gtk\nkde/client-kde")
        self._mksrc(
            "setup.py",
            """
from DistUtilsExtra.auto import setup

import warnings
warnings.filterwarnings('ignore', 'pipe2 set errno ENOSYS.*')

setup(
    name='foo',
    version='0.1',
    data_files=[('share/foo', ['gtk/client-gtk', 'kde/client-kde'])],
    scripts=['cli/client-cli'],
)
""",
        )

        (o, e, s) = self.setup_py(["build"])
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        # POT file should not be shown as not recognized
        self.assertNotIn("\n  po/foo.pot\n", o)

        pot = self._src_contents("po/foo.pot")

        self.assertNotIn('msgid "no"', pot)
        for i in range(2, 18):
            self.assertTrue(
                f'msgid "yes{int(i)}' in pot or f'msgid ""\n"yes{int(i)}' in pot,
                f"yes{int(i)}",
            )
        # above loop would match yes11 to yes1 as well, so test it explicitly
        self.assertIn('msgid "yes1"', pot)

    def test_standard_files(self):
        """Standard files (MANIFEST.in, COPYING, etc.)"""

        self._mksrc("AUTHORS")
        self._mksrc("COPYING")
        self._mksrc("LICENSE")
        self._mksrc("COPYING.LIB")
        self._mksrc("README.txt")
        self._mksrc("MANIFEST.in", content="# dummy")
        self._mksrc("MANIFEST")
        self._mksrc("NEWS")
        self._mksrc("TODO")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/usr/share/doc/foo/README.txt", f)
        self.assertIn("/usr/share/doc/foo/NEWS", f)
        ftext = "\n".join(f)
        self.assertNotIn("MANIFEST", ftext)
        self.assertNotIn("COPYING", ftext)
        self.assertNotIn("COPYING", ftext)
        self.assertNotIn("AUTHORS", ftext)
        self.assertNotIn("TODO", ftext)

        # sub-dir READMEs shouldn't be installed by default
        self.snapshot = None
        self._mksrc("extra/README")
        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  extra/README\n", o)

    def test_sdist(self):
        """default MANIFEST"""

        good = [
            "AUTHORS",
            "README.txt",
            "COPYING",
            "helpers.py",
            "foo/__init__.py",
            "foo/bar.py",
            "tests/all.py",
            "gui/x.desktop.in",
            "backend/foo.policy.in",
            "daemon/backend.conf",
            "x/y",
            "po/de.po",
            "po/foo.pot",
            ".quickly",
            "data/icons/16x16/apps/foo.png",
            "bin/foo",
            "backend/food",
            "backend/com.example.foo.service",
            "gtk/main.glade",
            "dist/extra.tar.gz",
        ]
        bad = [
            "po/de.mo",
            ".helpers.py.swp",
            ".bzr/index",
            ".svn/index",
            ".git/index",
            "bin/foo~",
            "backend/foo.pyc",
            "dist/foo-0.2.tar.gz",
            ".shelf/1",
            ".bzr/revs",
            ".git/config",
        ]

        for f in good + bad:
            self._mksrc(f)

        (_, e, s) = self.setup_py(["sdist"])
        self.assertEqual(e, "")
        self.assertEqual(s, 0)

        tarball = pathlib.Path(self.src) / "dist" / "foo-0.1.tar.gz"
        tar = subprocess.run(
            ["tar", "tf", str(tarball)], capture_output=True, text=True, check=True
        )
        tarball.unlink()

        manifest = [re.sub(r"^foo-0\.1/", "", f) for f in tar.stdout.splitlines()]

        for f in good:
            self.assertIn(f, manifest)
        for f in bad:
            self.assertNotIn(f, manifest)

    def test_ui(self):
        """GtkBuilder/Qt *.ui"""

        self._mksrc(
            "gtk/test.ui",
            b"""<?xml version="1.0"?>
<interface>
  <requires lib="gtk+" version="2.16"/>
  <object class="GtkWindow" id="window1">
    <property name="title" translatable="yes">my\xe2\x99\xa5</property>
    <child><placeholder/></child>
  </object>
</interface>""".decode(
                "UTF-8"
            ),
        )

        self._mksrc(
            "gtk/settings.ui",
            """<?xml version="1.0"?>
<!-- Generated with glade 3.18.3 -->
<interface domain="foobar">
  <requires lib="gtk+" version="2.16"/>
  <object class="GtkWindow" id="window2">
    <property name="title" translatable="yes">yes12</property>
    <child><placeholder/></child>
  </object>
</interface>""",
        )

        self._mksrc(
            "kde/mainwindow.ui",
            """<?xml version="1.0"?>
<ui version="4.0">
 <class>CrashDialog</class>
 <widget class="QDialog" name="CrashDialog">
 </widget>
</ui>
""",
        )

        self._mksrc("someweird.ui")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  someweird.ui\n", o)

        f = self.installed_files()
        self.assertIn("/usr/share/foo/test.ui", f)
        self.assertIn("/usr/share/foo/settings.ui", f)
        self.assertIn("/usr/share/foo/mainwindow.ui", f)
        ftext = "\n".join(f)
        self.assertNotIn("someweird", ftext)

    def test_manpages(self):
        """manpages"""

        self._mksrc("man/foo.1", '.TH foo 1 "Jan 01, 1900" "Joe Developer"')
        self._mksrc(
            "daemon/food.8",
            '." some comment\n.TH food 8 "Jan 01, 1900" "Joe Developer"',
        )
        self._mksrc("cruft/food.1", "")
        self._mksrc("daemon/notme.s", '.TH food 8 "Jan 01, 1900" "Joe Developer"')

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  cruft/food.1\n", o)
        self.assertIn("\n  daemon/notme.s\n", o)

        f = self.installed_files()
        self.assertIn("/usr/share/man/man1/foo.1", f)
        self.assertIn("/usr/share/man/man8/food.8", f)
        ftext = "\n".join(f)
        self.assertNotIn("food.1", ftext)
        self.assertNotIn("notme", ftext)

    def test_etc(self):
        """etc/*"""

        self._mksrc("etc/cron.daily/foo")
        self._mksrc("etc/foo.conf")
        self._mksrc("etc/init.d/foo", executable=True)
        d = os.path.join(self.src, "etc", "cron.weekly")
        os.mkdir(d)
        os.symlink(os.path.join("..", "cron.daily", "foo"), os.path.join(d, "foo"))

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

        f = self.installed_files()
        self.assertIn("/etc/cron.daily/foo", f)
        self.assertIn("/etc/cron.weekly/foo", f)
        self.assertIn("/etc/init.d/foo", f)
        self.assertIn("/etc/foo.conf", f)

        # verify that init script is executable
        self.assertTrue(
            os.access(os.path.join(self.install_tree, "etc", "init.d", "foo"), os.X_OK)
        )
        # verify that symlinks get preserved
        self.assertTrue(
            os.path.islink(os.path.join(self.install_tree, "etc", "cron.weekly", "foo"))
        )

        # check that we can install again into the same source tree
        (o, e, s) = self.setup_py(
            ["install", "--no-compile", "--prefix=/usr", f"--root={self.install_tree}"]
        )
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertNotIn("following files are not recognized", o)

    def test_requires_provides(self):
        """automatic requires/provides"""

        for needed_pkg in ["pkg_resources", "httplib2", "gi.repository.GLib"]:
            try:
                __import__(needed_pkg)
            except ImportError:
                self.fail(
                    f"You need to have {needed_pkg} installed"
                    f" for this test suite to work"
                )

        self._mksrc("foo/__init__.py", "")
        self._mksrc(
            "foo/stuff.py",
            """import xml.parsers.expat
import os, os.path, email.mime, setuptools.command.sdist
from email import header as h
import httplib2.iri2uri, unknown
from . bar import poke
from bar.poke import x
import grab_cli
import broken
""",
        )

        self._mksrc("foo/bar/__init__.py", "")
        self._mksrc("foo/bar/poke.py", "from . import broken\ndef x(): pass")
        self._mksrc(
            "foo/bar/broken.py", 'raise RuntimeError("cannot initialize system")'
        )

        self._mksrc("mymod.py", "import foo\nfrom foo.bar.poke import x")
        # trying to import this will cause setup.py to not process any args any more
        self._mksrc(
            "grab_cli.py",
            "from optparse import OptionParser\nOptionParser().parse_args()",
        )
        # trying to import this will break setup.py
        self._mksrc("broken.py", 'raise SystemError("cannot initialize system")')
        self._mksrc(
            "pygi.py", "from gi.repository import GLib\nimport gi.repository.GObject"
        )

        self._mksrc(
            "bin/foo-cli",
            """#!/usr/bin/python
import sys
import pkg_resources
import foo.bar
from httplib2 import iri2uri

print ('import iamnota.module')
""",
            executable=True,
        )

        # this shouldn't be treated specially
        self._mksrc("data/example-code/template.py", "import example.module")
        self._mksrc("data/example-code/mymod/__init__.py", "")
        self._mksrc("data/example-code/mymod/shiny.py", "import example.othermod")

        (o, e, s) = self.do_install()
        self.assertEqual(s, 0, e)
        self.assertEqual(e, "ERROR: Python module unknown not found\n")
        self.assertNotIn("following files are not recognized", o)

        inst = self.installed_files()
        self.assertIn("/usr/share/foo/example-code/template.py", inst)
        self.assertIn("/usr/share/foo/example-code/mymod/shiny.py", inst)
        for f in inst:
            if "template.py" in f or "shiny" in f:
                self.assertNotIn("packages", f)

        # parse .egg-info directory
        (o, e, s) = self.setup_py(["install_egg_info", "-d", self.install_tree])
        self.assertEqual(e, "ERROR: Python module unknown not found\n")
        in_egg_paths = [x for x in inst if ".egg-info/" in x]
        self.assertEqual(len(in_egg_paths), 4)  # Always 4 files in .egg-info directory

        pkginfo = self._installed_contents(
            [x for x in in_egg_paths if x.endswith("PKG-INFO")][0].strip(os.path.sep)
        ).splitlines()
        self.assertIn("Name: foo", pkginfo)

        # check provides
        prov = [
            prop.split(" ", 1)[1] for prop in pkginfo if prop.startswith("Provides: ")
        ]
        self.assertEqual(set(prov), set(["foo", "mymod", "broken", "grab_cli", "pygi"]))

        # check requires
        req = [
            prop.split(" ", 1)[1] for prop in pkginfo if prop.startswith("Requires: ")
        ]
        self.assertEqual(
            set(req),
            set(
                [
                    "httplib2",
                    "pkg_resources",
                    "gi.repository.GLib",
                    "gi.repository.GObject",
                    "setuptools.command.sdist",
                ]
            ),
        )

    def test_help_docbook(self):
        """Docbook XML help"""

        self._mksrc("help/C/index.docbook")
        self._mksrc("help/C/legal.xml")
        self._mksrc("help/C/figures/mainscreen.png")
        self._mksrc("help/de/index.docbook")
        self._mksrc("help/de/legal.xml")
        self._mksrc("help/de/figures/mainscreen.png")

        self._mksrc("help/weird.xml")
        self._mksrc("help/notme.png")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  help/weird.xml\n", o)
        self.assertIn("\n  help/notme.png\n", o)

        f = self.installed_files()
        self.assertIn("/usr/share/help/C/foo/index.docbook", f)
        self.assertIn("/usr/share/help/C/foo/legal.xml", f)
        self.assertIn("/usr/share/help/C/foo/figures/mainscreen.png", f)
        self.assertIn("/usr/share/help/de/foo/index.docbook", f)
        self.assertIn("/usr/share/help/de/foo/legal.xml", f)
        self.assertIn("/usr/share/help/de/foo/figures/mainscreen.png", f)

    def test_help_mallard(self):
        """Mallard XML help"""

        self._mksrc("help/C/index.page")
        self._mksrc("help/C/legal.page")
        self._mksrc("help/C/figures/mainscreen.png")
        self._mksrc("help/de/index.page")
        self._mksrc("help/de/legal.page")
        self._mksrc("help/de/figures/mainscreen.png")

        self._mksrc("help/weird.page")
        self._mksrc("help/notme.png")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  help/weird.page\n", o)
        self.assertIn("\n  help/notme.png\n", o)

        f = self.installed_files()
        self.assertIn("/usr/share/help/C/foo/index.page", f)
        self.assertIn("/usr/share/help/C/foo/legal.page", f)
        self.assertIn("/usr/share/help/C/foo/figures/mainscreen.png", f)
        self.assertIn("/usr/share/help/de/foo/index.page", f)
        self.assertIn("/usr/share/help/de/foo/legal.page", f)
        self.assertIn("/usr/share/help/de/foo/figures/mainscreen.png", f)

    def test_binary_files(self):
        """Binary files are ignored"""

        with open(os.path.join(self.src, "binary_trap"), "wb") as f:
            f.write(b"\x00\x01abc\xFF\xFE")
        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)
        self.assertIn("following files are not recognized", o)
        self.assertIn("\n  binary_trap\n", o)

        self.assert_egg_info_directory_is_present_and_well()

    def test_utf8_filenames(self):
        """UTF-8 file names"""

        bin_fname = b"a\xc3\xa4b.bin".decode("UTF-8")
        with open(os.path.join(self.src, bin_fname).encode("UTF-8"), "wb") as f:
            f.write(b"\x00\x01abc\xFF\xFE")

        (o, e, s) = self.do_install()
        self.assertEqual(e, "")
        self.assertEqual(s, 0)

        self.assert_egg_info_directory_is_present_and_well()

        self.assertIn("following files are not recognized", o)
        # this might not be the correct file name when the locale is e. g. C
        self.assertIn("b.bin\n", o)

    #
    # helper methods
    #

    def setup_py(self, args):
        """Run setup.py with given arguments.

        For convenience, this snapshots the tree if no snapshot exists yet.

        Return (out, err, exitcode) triple.
        """
        if not self.snapshot:
            self.do_snapshot()

        env = os.environ.copy()
        oldcwd = os.getcwd()
        if "PYTHONPATH" in env:
            env["PYTHONPATH"] = oldcwd + os.pathsep + env["PYTHONPATH"]
        else:
            env["PYTHONPATH"] = oldcwd
        # unset envvars that alter results
        env.pop("LINGUAS", "")
        env.pop("PYTHONDONTWRITEBYTECODE", "")
        os.chdir(self.src)
        s = subprocess.Popen(
            ["/proc/self/exe", "setup.py"] + args,
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        (out, err) = s.communicate()
        out = out.decode()
        err = err.decode()
        os.chdir(oldcwd)

        return (out, err, s.returncode)

    def do_install(self):
        """Run setup.py install into temporary tree.

        Return (out, err, exitcode) triple.
        """
        self.install_tree = tempfile.mkdtemp()

        self.setup_py(["build"])
        return self.setup_py(
            [
                "install",
                "--no-compile",
                "--skip-build",
                "--prefix=/usr",
                "--install-data=/usr",
                "--install-scripts=/usr/bin",
                f"--root={self.install_tree}",
            ]
        )

    def installed_files(self):
        """Return list of file paths in install tree."""

        result = []
        for root, _, files in os.walk(self.install_tree):
            assert root.startswith(self.install_tree)
            r = root[len(self.install_tree) :]
            for f in files:
                result.append(os.path.join(r, f))
        return result

    def _mksrc(self, path, content=None, executable=False):
        """Create a file in the test source tree."""

        path = os.path.join(self.src, path)
        directory = os.path.dirname(path)
        if not os.path.isdir(directory):
            os.makedirs(directory)
        with open(path, "wb") as f:
            if content is None:
                # default content, to spot with diff
                f.write(b"dummy")
            else:
                f.write(f"{content}\n".encode("UTF-8"))

        if executable:
            os.chmod(path, 0o755)

    def do_snapshot(self):
        """Snapshot source tree.

        This should be called after a test set up all source files.
        """
        assert self.snapshot is None, "snapshot already taken"

        self.snapshot = tempfile.mkdtemp()
        shutil.copytree(self.src, os.path.join(self.snapshot, "s"), symlinks=True)

    def diff_snapshot(self):
        """Compare source tree to snapshot, excluding known offenders.

        Check https://github.com/pypa/setuptools/issues/1347 for reference

        Return diff -Nur output.
        """
        assert self.snapshot, "no snapshot taken"
        diff = subprocess.run(
            [
                "diff",
                "-x",
                "foo.pot",
                "-x",
                "*.pyc",
                "-x",
                "*.egg-info",
                "-Nur",
                os.path.join(self.snapshot, "s"),
                self.src,
            ],
            capture_output=True,
            check=False,
            text=True,
        )
        return diff.stdout

    def _mkpo(self):
        """Create some example po files."""

        self._mksrc("po/POTFILES.in", "")
        self._mksrc(
            "po/de.po",
            '''msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8\\n"

msgid "Good morning"
msgstr "Guten Morgen"

msgid "Hello"
msgstr "Hallo"''',
        )
        self._mksrc(
            "po/fr.po",
            '''msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8\\n"

msgid "Good morning"
msgstr "Bonjour"''',
        )

    def _mk_i18n_source(self):
        """Create some example source files with gettext calls"""

        self._mksrc(
            "gtk/main.py",
            """print (_("yes1"))
print ("no1")
print (__("no2"))
x = _('yes2 %s') % y

def f():
    print (_("yes3"))
    return _('yes6')""",
        )

        self._mksrc(
            "helpers.py",
            '''
print (f(_("yes4")))
print (_(\'\'\'yes5
even more
lines\'\'\'))
print (_("""yes6
more lines"""))
print (\'\'\'no3
boo\'\'\')
print ("""no4
more""")''',
        )

        self._mksrc(
            "gui/foo.desktop.in",
            """[Desktop Entry]
_Name=yes7
_Comment=yes8
Icon=no5
Exec=/usr/bin/foo""",
        )

        self._mksrc(
            "daemon/com.example.foo.policy.in",
            """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
 "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
 "http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
  <action id="com.example.foo.greet">
    <_description>yes9</_description>
    <_message>yes10</_message>
    <defaults>
      <allow_active>no6</allow_active>
    </defaults>
  </action>
</policyconfig>""",
        )

        self._mksrc(
            "gtk/test.ui",
            """<?xml version="1.0"?>
<interface>
  <requires lib="gtk+" version="2.16"/>
  <object class="GtkWindow" id="window1">
    <property name="title" translatable="yes">yes11</property>
    <child><placeholder/></child>
  </object>
</interface>""",
        )

        self._mksrc(
            "data/settings.ui",
            """<?xml version="1.0"?>
<interface domain="foobar">
  <requires lib="gtk+" version="2.16"/>
  <object class="GtkWindow" id="window1">
    <property name="title" translatable="yes">yes12</property>
    <child><placeholder/></child>
  </object>
</interface>""",
        )

        self._mksrc("Makefile", 'echo _("no7")')

        # Executables without *.py extension
        self._mksrc(
            "gtk/foo-gtk", '#!/usr/bin/python\nprint (_("yes13"))', executable=True
        )
        self._mksrc(
            "cli/foo-cli", "#!/usr/bin/env python\nprint (_('yes14'))", executable=True
        )
        self._mksrc("daemon/foobarize", '#!/usr/bin/flex\np _("no8")', executable=True)

    def _src_contents(self, path):
        full_path = pathlib.Path(self.src) / path
        return full_path.read_text("utf-8")

    def _installed_contents(self, path):
        full_path = pathlib.Path(self.install_tree) / path
        return full_path.read_text("utf-8")


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