summaryrefslogtreecommitdiff
path: root/distutils2/tests/test_util.py
blob: ea9535fbdb8ddc63bcec5f131b5d3cf95dfb2364 (plain)
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
"""Tests for distutils2.util."""
import os
import sys
import time
import logging
import tempfile
import textwrap
import subprocess
from StringIO import StringIO

from distutils2.errors import (
    PackagingPlatformError, PackagingFileError,
    PackagingExecError, InstallationException)
from distutils2 import util
from distutils2.dist import Distribution
from distutils2.util import (
    convert_path, change_root, split_quoted, strtobool, run_2to3,
    get_compiler_versions, _MAC_OS_X_LD_VERSION, byte_compile, find_packages,
    spawn, get_pypirc_path, generate_pypirc, read_pypirc, resolve_name, iglob,
    RICH_GLOB, egginfo_to_distinfo, is_setuptools, is_distutils, is_packaging,
    get_install_method, cfg_to_args, generate_setup_py, encode_multipart,
    parse_requires)

from distutils2.tests import support, unittest
from distutils2.tests.test_config import SETUP_CFG
from distutils2.tests.support import assert_python_ok, assert_python_failure


PYPIRC = """\
[distutils]
index-servers =
    pypi
    server1

[pypi]
username:me
password:xxxx

[server1]
repository:http://example.com
username:tarek
password:secret
"""

PYPIRC_OLD = """\
[server-login]
username:tarek
password:secret
"""

WANTED = """\
[distutils]
index-servers =
    pypi

[pypi]
username:tarek
password:xxx
"""

EXPECTED_MULTIPART_OUTPUT = [
    '---x',
    'Content-Disposition: form-data; name="username"',
    '',
    'wok',
    '---x',
    'Content-Disposition: form-data; name="password"',
    '',
    'secret',
    '---x',
    'Content-Disposition: form-data; name="picture"; filename="wok.png"',
    '',
    'PNG89',
    '---x--',
    '',
]


class FakePopen(object):
    test_class = None

    def __init__(self, args, bufsize=0, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=False,
                 shell=False, cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=()):
        if isinstance(args, basestring):
            args = args.split()
        self.cmd = args[0]
        exes = self.test_class._exes
        if self.cmd not in exes:
            # we don't want to call the system, returning an empty
            # output so it doesn't match
            self.stdout = StringIO()
            self.stderr = StringIO()
        else:
            self.stdout = StringIO(exes[self.cmd])
            self.stderr = StringIO()

    def communicate(self, input=None, timeout=None):
        return self.stdout.read(), self.stderr.read()

    def wait(self, timeout=None):
        return 0


class UtilTestCase(support.EnvironRestorer,
                   support.TempdirManager,
                   support.LoggingCatcher,
                   unittest.TestCase):

    restore_environ = ['HOME', 'PLAT']

    def setUp(self):
        super(UtilTestCase, self).setUp()
        self.addCleanup(os.chdir, os.getcwd())
        tempdir = self.mkdtemp()
        self.rc = os.path.join(tempdir, '.pypirc')
        os.environ['HOME'] = tempdir
        os.chdir(tempdir)
        # saving the environment
        self.name = os.name
        self.platform = sys.platform
        self.version = sys.version
        self.sep = os.sep
        self.join = os.path.join
        self.isabs = os.path.isabs
        self.splitdrive = os.path.splitdrive

        # patching os.uname
        if hasattr(os, 'uname'):
            self.uname = os.uname
            self._uname = os.uname()
        else:
            self.uname = None
            self._uname = None
        os.uname = self._get_uname

    def _get_uname(self):
        return self._uname

    def tearDown(self):
        # getting back the environment
        os.name = self.name
        sys.platform = self.platform
        sys.version = self.version
        os.sep = self.sep
        os.path.join = self.join
        os.path.isabs = self.isabs
        os.path.splitdrive = self.splitdrive
        if self.uname is not None:
            os.uname = self.uname
        else:
            del os.uname
        super(UtilTestCase, self).tearDown()

    def mock_popen(self):
        self.old_find_executable = util.find_executable
        util.find_executable = self._find_executable
        self._exes = {}
        self.old_popen = subprocess.Popen
        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr
        FakePopen.test_class = self
        subprocess.Popen = FakePopen
        self.addCleanup(self.unmock_popen)

    def unmock_popen(self):
        util.find_executable = self.old_find_executable
        subprocess.Popen = self.old_popen
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

    def test_set_platform(self):
        self.addCleanup(util.set_platform, util.get_platform())
        util.set_platform("fake")
        self.assertEqual("fake", util.get_platform())

    def test_convert_path(self):
        # linux/mac
        os.sep = '/'

        def _join(path):
            return '/'.join(path)
        os.path.join = _join

        self.assertEqual(convert_path('/home/to/my/stuff'),
                         '/home/to/my/stuff')

        # win
        os.sep = '\\'

        def _join(*path):
            return '\\'.join(path)
        os.path.join = _join

        self.assertRaises(ValueError, convert_path, '/home/to/my/stuff')
        self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/')

        self.assertEqual(convert_path('home/to/my/stuff'),
                         'home\\to\\my\\stuff')
        self.assertEqual(convert_path('.'),
                         os.curdir)

    def test_change_root(self):
        # linux/mac
        os.name = 'posix'

        def _isabs(path):
            return path[0] == '/'
        os.path.isabs = _isabs

        def _join(*path):
            return '/'.join(path)
        os.path.join = _join

        self.assertEqual(change_root('/root', '/old/its/here'),
                         '/root/old/its/here')
        self.assertEqual(change_root('/root', 'its/here'),
                         '/root/its/here')

        # windows
        os.name = 'nt'

        def _isabs(path):
            return path.startswith('c:\\')
        os.path.isabs = _isabs

        def _splitdrive(path):
            if path.startswith('c:'):
                return '', path.replace('c:', '')
            return '', path
        os.path.splitdrive = _splitdrive

        def _join(*path):
            return '\\'.join(path)
        os.path.join = _join

        self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'),
                         'c:\\root\\old\\its\\here')
        self.assertEqual(change_root('c:\\root', 'its\\here'),
                         'c:\\root\\its\\here')

        # BugsBunny os (it's a great os)
        os.name = 'BugsBunny'
        self.assertRaises(PackagingPlatformError,
                          change_root, 'c:\\root', 'its\\here')

        # XXX platforms to be covered: os2, mac

    def test_split_quoted(self):
        self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'),
                         ['one', 'two', 'three', 'four'])

    def test_strtobool(self):
        yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
        no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N')

        for y in yes:
            self.assertTrue(strtobool(y))

        for n in no:
            self.assertFalse(strtobool(n))

    def test_find_exe_version(self):
        # the ld version scheme under MAC OS is:
        #   ^@(#)PROGRAM:ld  PROJECT:ld64-VERSION
        #
        # where VERSION is a 2-digit number for major
        # revisions. For instance under Leopard, it's
        # currently 77
        #
        # Dots are used when branching is done.
        #
        # The SnowLeopard ld64 is currently 95.2.12

        for output, version in (('@(#)PROGRAM:ld  PROJECT:ld64-77', '77'),
                                ('@(#)PROGRAM:ld  PROJECT:ld64-95.2.12',
                                 '95.2.12')):
            result = _MAC_OS_X_LD_VERSION.search(output)
            self.assertEqual(result.group(1), version)

    def _find_executable(self, name):
        if name in self._exes:
            return name
        return None

    def test_get_compiler_versions(self):
        self.mock_popen()
        # get_versions calls distutils.spawn.find_executable on
        # 'gcc', 'ld' and 'dllwrap'
        self.assertEqual(get_compiler_versions(), (None, None, None))

        # Let's fake we have 'gcc' and it returns '3.4.5'
        self._exes['gcc'] = 'gcc (GCC) 3.4.5 (mingw special)\nFSF'
        res = get_compiler_versions()
        self.assertEqual(str(res[0]), '3.4.5')

        # and let's see what happens when the version
        # doesn't match the regular expression
        # (\d+\.\d+(\.\d+)*)
        self._exes['gcc'] = 'very strange output'
        res = get_compiler_versions()
        self.assertEqual(res[0], None)

        # same thing for ld
        if sys.platform != 'darwin':
            self._exes['ld'] = 'GNU ld version 2.17.50 20060824'
            res = get_compiler_versions()
            self.assertEqual(str(res[1]), '2.17.50')
            self._exes['ld'] = '@(#)PROGRAM:ld  PROJECT:ld64-77'
            res = get_compiler_versions()
            self.assertEqual(res[1], None)
        else:
            self._exes['ld'] = 'GNU ld version 2.17.50 20060824'
            res = get_compiler_versions()
            self.assertEqual(res[1], None)
            self._exes['ld'] = '@(#)PROGRAM:ld  PROJECT:ld64-77'
            res = get_compiler_versions()
            self.assertEqual(str(res[1]), '77')

        # and dllwrap
        self._exes['dllwrap'] = 'GNU dllwrap 2.17.50 20060824\nFSF'
        res = get_compiler_versions()
        self.assertEqual(str(res[2]), '2.17.50')
        self._exes['dllwrap'] = 'Cheese Wrap'
        res = get_compiler_versions()
        self.assertEqual(res[2], None)

    @unittest.skipUnless(hasattr(sys, 'dont_write_bytecode'),
                         'sys.dont_write_bytecode not supported')
    def test_byte_compile_under_B(self):
        # make sure byte compilation works under -B (dont_write_bytecode)
        self.addCleanup(setattr, sys, 'dont_write_bytecode',
                        sys.dont_write_bytecode)
        sys.dont_write_bytecode = True
        byte_compile([])

    def test_newer(self):
        self.assertRaises(PackagingFileError, util.newer, 'xxx', 'xxx')
        self.newer_f1 = self.mktempfile()
        time.sleep(1)
        self.newer_f2 = self.mktempfile()
        self.assertTrue(util.newer(self.newer_f2.name, self.newer_f1.name))

    def test_find_packages(self):
        # let's create a structure we want to scan:
        #
        #   pkg1
        #     __init__
        #     pkg2
        #       __init__
        #     pkg3
        #       __init__
        #       pkg6
        #           __init__
        #     pkg4    <--- not a pkg
        #       pkg8
        #          __init__
        #   pkg5
        #     __init__
        #
        root = self.mkdtemp()
        pkg1 = os.path.join(root, 'pkg1')
        os.makedirs(os.path.join(pkg1, 'pkg2'))
        os.makedirs(os.path.join(pkg1, 'pkg3', 'pkg6'))
        os.makedirs(os.path.join(pkg1, 'pkg4', 'pkg8'))
        os.makedirs(os.path.join(root, 'pkg5'))
        self.write_file((pkg1, '__init__.py'))
        self.write_file((pkg1, 'pkg2', '__init__.py'))
        self.write_file((pkg1, 'pkg3', '__init__.py'))
        self.write_file((pkg1, 'pkg3', 'pkg6', '__init__.py'))
        self.write_file((pkg1, 'pkg4', 'pkg8', '__init__.py'))
        self.write_file((root, 'pkg5', '__init__.py'))

        res = find_packages([root], ['pkg1.pkg2'])
        self.assertEqual(sorted(res),
                         ['pkg1', 'pkg1.pkg3', 'pkg1.pkg3.pkg6', 'pkg5'])

    def test_parse_requires(self):
        req_file = os.path.join(os.path.dirname(__file__), 'requires.txt')
        expected_requires = ['setuptools', 'zope.browser', 'zope.component',
                'zope.configuration', 'zope.contenttype', 'zope.event',
                'zope.exceptions', 'zope.i18n', 'zope.interface',
                'zope.location', 'zope.proxy', 'zope.security']
        requires = parse_requires(req_file)
        self.assertEqual(requires, expected_requires)

    def test_resolve_name(self):
        # test raw module name
        tmpdir = self.mkdtemp()
        sys.path.append(tmpdir)
        self.addCleanup(sys.path.remove, tmpdir)
        self.write_file((tmpdir, 'hello.py'), '')

        os.makedirs(os.path.join(tmpdir, 'a', 'b'))
        self.write_file((tmpdir, 'a', '__init__.py'), '')
        self.write_file((tmpdir, 'a', 'b', '__init__.py'), '')
        self.write_file((tmpdir, 'a', 'b', 'c.py'), 'class Foo: pass')
        self.write_file((tmpdir, 'a', 'b', 'd.py'), textwrap.dedent("""\
                         class FooBar:
                             class Bar:
                                 def baz(self):
                                     pass
                            """))

        # check Python, C and built-in module
        self.assertEqual(resolve_name('hello').__name__, 'hello')
        self.assertEqual(resolve_name('_csv').__name__, '_csv')
        self.assertEqual(resolve_name('sys').__name__, 'sys')

        # test module.attr
        self.assertIs(resolve_name('__builtin__.str'), str)
        self.assertIsNone(resolve_name('hello.__doc__'))
        self.assertEqual(resolve_name('a.b.c.Foo').__name__, 'Foo')
        self.assertEqual(resolve_name('a.b.d.FooBar.Bar.baz').__name__, 'baz')

        # error if module not found
        self.assertRaises(ImportError, resolve_name, 'nonexistent')
        self.assertRaises(ImportError, resolve_name, 'non.existent')
        self.assertRaises(ImportError, resolve_name, 'a.no')
        self.assertRaises(ImportError, resolve_name, 'a.b.no')
        self.assertRaises(ImportError, resolve_name, 'a.b.no.no')
        self.assertRaises(ImportError, resolve_name, 'inva-lid')

        # looking up built-in names is not supported
        self.assertRaises(ImportError, resolve_name, 'str')

        # error if module found but not attr
        self.assertRaises(ImportError, resolve_name, 'a.b.Spam')
        self.assertRaises(ImportError, resolve_name, 'a.b.c.Spam')

    @support.requires_py26_min
    @support.skip_2to3_optimize
    def test_run_2to3_on_code(self):
        content = "print 'test'"
        converted_content = "print('test')"
        file_handle = self.mktempfile()
        file_name = file_handle.name
        file_handle.write(content)
        file_handle.flush()
        file_handle.seek(0)
        run_2to3([file_name])
        new_content = "".join(file_handle.read())
        file_handle.close()
        self.assertEqual(new_content, converted_content)

    @support.requires_py26_min
    @support.skip_2to3_optimize
    def test_run_2to3_on_doctests(self):
        # to check if text files containing doctests only get converted.
        content = ">>> print 'test'\ntest\n"
        converted_content = ">>> print('test')\ntest\n\n"
        file_handle = self.mktempfile()
        file_name = file_handle.name
        file_handle.write(content)
        file_handle.flush()
        file_handle.seek(0)
        run_2to3([file_name], doctests_only=True)
        new_content = "".join(file_handle.readlines())
        file_handle.close()
        self.assertEqual(new_content, converted_content)

    @unittest.skipUnless(os.name in ('nt', 'posix'),
                         'runs only under posix or nt')
    def test_spawn(self):
        tmpdir = self.mkdtemp()

        # creating something executable
        # through the shell that returns 1
        if os.name == 'posix':
            exe = os.path.join(tmpdir, 'foo.sh')
            self.write_file(exe, '#!/bin/sh\nexit 1')
            os.chmod(exe, 0777)
        else:
            exe = os.path.join(tmpdir, 'foo.bat')
            self.write_file(exe, 'exit 1')

        os.chmod(exe, 0777)
        self.assertRaises(PackagingExecError, spawn, [exe])

        # now something that works
        if os.name == 'posix':
            exe = os.path.join(tmpdir, 'foo.sh')
            self.write_file(exe, '#!/bin/sh\nexit 0')
            os.chmod(exe, 0777)
        else:
            exe = os.path.join(tmpdir, 'foo.bat')
            self.write_file(exe, 'exit 0')

        os.chmod(exe, 0777)
        spawn([exe])  # should work without any error

    def test_server_registration(self):
        # This test makes sure we know how to:
        # 1. handle several sections in .pypirc
        # 2. handle the old format

        # new format
        self.write_file(self.rc, PYPIRC)
        config = read_pypirc()

        config = sorted(config.items())
        expected = [('password', 'xxxx'), ('realm', 'pypi'),
                    ('repository', 'http://pypi.python.org/pypi'),
                    ('server', 'pypi'), ('username', 'me')]
        self.assertEqual(config, expected)

        # old format
        self.write_file(self.rc, PYPIRC_OLD)
        config = read_pypirc()
        config = sorted(config.items())
        expected = [('password', 'secret'), ('realm', 'pypi'),
                    ('repository', 'http://pypi.python.org/pypi'),
                    ('server', 'server-login'), ('username', 'tarek')]
        self.assertEqual(config, expected)

    def test_server_empty_registration(self):
        rc = get_pypirc_path()
        self.assertFalse(os.path.exists(rc))
        generate_pypirc('tarek', 'xxx')
        self.assertTrue(os.path.exists(rc))
        f = open(rc)
        try:
            content = f.read()
        finally:
            f.close()
        self.assertEqual(content, WANTED)

    def test_cfg_to_args(self):
        opts = {'description-file': 'README', 'extra-files': '',
                'setup-hooks': 'distutils2.tests.test_config.version_hook'}
        self.write_file('setup.cfg', SETUP_CFG % opts, encoding='utf-8')
        self.write_file('README', 'loooong description')

        args = cfg_to_args()
        # use Distribution to get the contents of the setup.cfg file
        dist = Distribution()
        dist.parse_config_files()
        metadata = dist.metadata

        self.assertEqual(args['name'], metadata['Name'])
        # + .dev1 because the test SETUP_CFG also tests a hook function in
        # test_config.py for appending to the version string
        self.assertEqual(args['version'] + '.dev1', metadata['Version'])
        self.assertEqual(args['author'], metadata['Author'])
        self.assertEqual(args['author_email'], metadata['Author-Email'])
        self.assertEqual(args['maintainer'], metadata['Maintainer'])
        self.assertEqual(args['maintainer_email'],
                         metadata['Maintainer-Email'])
        self.assertEqual(args['description'], metadata['Summary'])
        self.assertEqual(args['long_description'], metadata['Description'])
        self.assertEqual(args['classifiers'], metadata['Classifier'])
        self.assertEqual(args['requires'], metadata['Requires-Dist'])
        self.assertEqual(args['provides'], metadata['Provides-Dist'])

        self.assertEqual(args['package_dir'].get(''), dist.package_dir)
        self.assertEqual(args['packages'], dist.packages)
        self.assertEqual(args['scripts'], dist.scripts)
        self.assertEqual(args['py_modules'], dist.py_modules)

    def test_generate_setup_py(self):
        os.chdir(self.mkdtemp())
        self.write_file('setup.cfg', textwrap.dedent("""\
            [metadata]
            name = SPAM
            classifier = Programming Language :: Python
            """))
        generate_setup_py()
        self.assertTrue(os.path.exists('setup.py'), 'setup.py not created')
        rc, out, err = assert_python_ok('setup.py', '--name')
        self.assertEqual(out, 'SPAM\n')
        self.assertEqual(err, '')

        # a generated setup.py should complain if no setup.cfg is present
        os.unlink('setup.cfg')
        rc, out, err = assert_python_failure('setup.py', '--name')
        self.assertIn('setup.cfg', err)

    def test_encode_multipart(self):
        fields = [('username', 'wok'), ('password', 'secret')]
        files = [('picture', 'wok.png', 'PNG89')]
        content_type, body = encode_multipart(fields, files, '-x')
        self.assertEqual('multipart/form-data; boundary=-x', content_type)
        self.assertEqual(EXPECTED_MULTIPART_OUTPUT, body.split('\r\n'))


class GlobTestCaseBase(support.TempdirManager,
                       support.LoggingCatcher,
                       unittest.TestCase):

    def build_files_tree(self, files):
        tempdir = self.mkdtemp()
        for filepath in files:
            is_dir = filepath.endswith('/')
            filepath = os.path.join(tempdir, *filepath.split('/'))
            if is_dir:
                dirname = filepath
            else:
                dirname = os.path.dirname(filepath)
            if dirname and not os.path.exists(dirname):
                os.makedirs(dirname)
            if not is_dir:
                self.write_file(filepath, 'babar')
        return tempdir

    @staticmethod
    def os_dependent_path(path):
        path = path.rstrip('/').split('/')
        return os.path.join(*path)

    def clean_tree(self, spec):
        files = []
        for path, includes in spec.items():
            if includes:
                files.append(self.os_dependent_path(path))
        return files


class GlobTestCase(GlobTestCaseBase):

    def assertGlobMatch(self, glob, spec):
        tempdir = self.build_files_tree(spec)
        expected = self.clean_tree(spec)
        os.chdir(tempdir)
        result = list(iglob(glob))
        self.assertItemsEqual(expected, result)

    def test_regex_rich_glob(self):
        matches = RICH_GLOB.findall(
                                r"babar aime les {fraises} est les {huitres}")
        self.assertEqual(["fraises", "huitres"], matches)

    def test_simple_glob(self):
        glob = '*.tp?'
        spec = {'coucou.tpl': True,
                 'coucou.tpj': True,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_simple_glob_in_dir(self):
        glob = os.path.join('babar', '*.tp?')
        spec = {'babar/coucou.tpl': True,
                 'babar/coucou.tpj': True,
                 'babar/toto.bin': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_recursive_glob_head(self):
        glob = os.path.join('**', 'tip', '*.t?l')
        spec = {'babar/zaza/zuzu/tip/coucou.tpl': True,
                 'babar/z/tip/coucou.tpl': True,
                 'babar/tip/coucou.tpl': True,
                 'babar/zeop/tip/babar/babar.tpl': False,
                 'babar/z/tip/coucou.bin': False,
                 'babar/toto.bin': False,
                 'zozo/zuzu/tip/babar.tpl': True,
                 'zozo/tip/babar.tpl': True,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_recursive_glob_tail(self):
        glob = os.path.join('babar', '**')
        spec = {'babar/zaza/': True,
                'babar/zaza/zuzu/': True,
                'babar/zaza/zuzu/babar.xml': True,
                'babar/zaza/zuzu/toto.xml': True,
                'babar/zaza/zuzu/toto.csv': True,
                'babar/zaza/coucou.tpl': True,
                'babar/bubu.tpl': True,
                'zozo/zuzu/tip/babar.tpl': False,
                'zozo/tip/babar.tpl': False,
                'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_recursive_glob_middle(self):
        glob = os.path.join('babar', '**', 'tip', '*.t?l')
        spec = {'babar/zaza/zuzu/tip/coucou.tpl': True,
                 'babar/z/tip/coucou.tpl': True,
                 'babar/tip/coucou.tpl': True,
                 'babar/zeop/tip/babar/babar.tpl': False,
                 'babar/z/tip/coucou.bin': False,
                 'babar/toto.bin': False,
                 'zozo/zuzu/tip/babar.tpl': False,
                 'zozo/tip/babar.tpl': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_glob_set_tail(self):
        glob = os.path.join('bin', '*.{bin,sh,exe}')
        spec = {'bin/babar.bin': True,
                 'bin/zephir.sh': True,
                 'bin/celestine.exe': True,
                 'bin/cornelius.bat': False,
                 'bin/cornelius.xml': False,
                 'toto/yurg': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_glob_set_middle(self):
        glob = os.path.join('xml', '{babar,toto}.xml')
        spec = {'xml/babar.xml': True,
                 'xml/toto.xml': True,
                 'xml/babar.xslt': False,
                 'xml/cornelius.sgml': False,
                 'xml/zephir.xml': False,
                 'toto/yurg.xml': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_glob_set_head(self):
        glob = os.path.join('{xml,xslt}', 'babar.*')
        spec = {'xml/babar.xml': True,
                 'xml/toto.xml': False,
                 'xslt/babar.xslt': True,
                 'xslt/toto.xslt': False,
                 'toto/yurg.xml': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_glob_all(self):
        dirs = '{%s,%s}' % (os.path.join('xml', '*'),
                            os.path.join('xslt', '**'))
        glob = os.path.join(dirs, 'babar.xml')
        spec = {'xml/a/babar.xml': True,
                 'xml/b/babar.xml': True,
                 'xml/a/c/babar.xml': False,
                 'xslt/a/babar.xml': True,
                 'xslt/b/babar.xml': True,
                 'xslt/a/c/babar.xml': True,
                 'toto/yurg.xml': False,
                 'Donotwant': False}
        self.assertGlobMatch(glob, spec)

    def test_invalid_glob_pattern(self):
        invalids = [
            'ppooa**',
            'azzaeaz4**/',
            '/**ddsfs',
            '**##1e"&e',
            'DSFb**c009',
            '{',
            '{aaQSDFa',
            '}',
            'aQSDFSaa}',
            '{**a,',
            ',**a}',
            '{a**,',
            ',b**}',
            '{a**a,babar}',
            '{bob,b**z}',
        ]
        for pattern in invalids:
            self.assertRaises(ValueError, iglob, pattern)


PKG_INFO = '''\
Metadata-Version: 1.1
Name: hello
Version: 0.1.1
Summary: Hello World
Home-page: https://example.com
Author: John Doe
Author-email: j.doe@example.com
License: UNKNOWN
Download-URL: https://example.com/tarball/master
Description: UNKNOWN
Platform: Any
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.2
Classifier: Intended Audience :: Developers
Classifier: Environment :: Console
Provides: hello
'''


class EggInfoToDistInfoTestCase(support.TempdirManager,
                                support.LoggingCatcher,
                                unittest.TestCase):

    def get_metadata_file_paths(self, distinfo_path):
        req_metadata_files = ['METADATA', 'RECORD', 'INSTALLER']
        metadata_file_paths = []
        for metadata_file in req_metadata_files:
            path = os.path.join(distinfo_path, metadata_file)
            metadata_file_paths.append(path)
        return metadata_file_paths

    def test_egginfo_to_distinfo_setuptools(self):
        distinfo = 'hello-0.1.1-py3.3.dist-info'
        egginfo = 'hello-0.1.1-py3.3.egg-info'
        dirs = [egginfo]
        files = ['hello.py', 'hello.pyc']
        extra_metadata = ['dependency_links.txt', 'entry_points.txt',
                          'not-zip-safe', ('PKG-INFO', PKG_INFO),
                          'top_level.txt', 'SOURCES.txt']
        for f in extra_metadata:
            if isinstance(f, tuple):
                f, content = f
            else:
                content = 'XXX'
            files.append((os.path.join(egginfo, f), content))

        tempdir, record_file = self.build_dist_tree(files, dirs)
        distinfo_path = os.path.join(tempdir, distinfo)
        egginfo_path = os.path.join(tempdir, egginfo)
        metadata_file_paths = self.get_metadata_file_paths(distinfo_path)

        egginfo_to_distinfo(record_file)
        # test that directories and files get created
        self.assertTrue(os.path.isdir(distinfo_path))
        self.assertTrue(os.path.isdir(egginfo_path))

        for mfile in metadata_file_paths:
            self.assertTrue(os.path.isfile(mfile))

    def test_egginfo_to_distinfo_distutils(self):
        distinfo = 'hello-0.1.1-py3.3.dist-info'
        egginfo = 'hello-0.1.1-py3.3.egg-info'
        # egginfo is a file in distutils which contains the metadata
        files = ['hello.py', 'hello.pyc', (egginfo, PKG_INFO)]

        tempdir, record_file = self.build_dist_tree(files, dirs=[])
        distinfo_path = os.path.join(tempdir, distinfo)
        egginfo_path = os.path.join(tempdir, egginfo)
        metadata_file_paths = self.get_metadata_file_paths(distinfo_path)
        egginfo_to_distinfo(record_file)
        # test that directories and files get created
        self.assertTrue(os.path.isdir(distinfo_path))
        self.assertTrue(os.path.isfile(egginfo_path))

        for mfile in metadata_file_paths:
            self.assertTrue(os.path.isfile(mfile))

    def build_dist_tree(self, files, dirs):
        tempdir = self.mkdtemp()
        record_file_path = os.path.join(tempdir, 'RECORD')
        file_paths, dir_paths = ([], [])
        for d in dirs:
            path = os.path.join(tempdir, d)
            os.makedirs(path)
            dir_paths.append(path)
        for f in files:
            if isinstance(f, (list, tuple)):
                f, content = f
            else:
                content = ''

            path = os.path.join(tempdir, f)
            _f = open(path, 'w')
            try:
                _f.write(content)
            finally:
                _f.close()
            file_paths.append(path)

        record_file = open(record_file_path, 'w')
        try:
            for fpath in file_paths:
                record_file.write(fpath + '\n')
            for dpath in dir_paths:
                record_file.write(dpath + '\n')
        finally:
            record_file.close()
        return (tempdir, record_file_path)


class PackagingLibChecks(support.TempdirManager,
                         support.LoggingCatcher,
                         unittest.TestCase):

    def setUp(self):
        super(PackagingLibChecks, self).setUp()
        self._empty_dir = self.mkdtemp()

    def test_empty_package_is_not_based_on_anything(self):
        self.assertFalse(is_setuptools(self._empty_dir))
        self.assertFalse(is_distutils(self._empty_dir))
        self.assertFalse(is_packaging(self._empty_dir))

    def test_setup_py_importing_setuptools_is_setuptools_based(self):
        self.assertTrue(is_setuptools(self._setuptools_setup_py_pkg()))

    def test_egg_info_dir_and_setup_py_is_setuptools_based(self):
        self.assertTrue(is_setuptools(self._setuptools_egg_info_pkg()))

    def test_egg_info_and_non_setuptools_setup_py_is_setuptools_based(self):
        self.assertTrue(is_setuptools(self._egg_info_with_no_setuptools()))

    def test_setup_py_not_importing_setuptools_is_not_setuptools_based(self):
        self.assertFalse(is_setuptools(self._random_setup_py_pkg()))

    def test_setup_py_importing_distutils_is_distutils_based(self):
        self.assertTrue(is_distutils(self._distutils_setup_py_pkg()))

    def test_pkg_info_file_and_setup_py_is_distutils_based(self):
        self.assertTrue(is_distutils(self._distutils_pkg_info()))

    def test_pkg_info_and_non_distutils_setup_py_is_distutils_based(self):
        self.assertTrue(is_distutils(self._pkg_info_with_no_distutils()))

    def test_setup_py_not_importing_distutils_is_not_distutils_based(self):
        self.assertFalse(is_distutils(self._random_setup_py_pkg()))

    def test_setup_cfg_with_no_metadata_section_is_not_packaging_based(self):
        self.assertFalse(is_packaging(self._setup_cfg_with_no_metadata_pkg()))

    def test_setup_cfg_with_valid_metadata_section_is_packaging_based(self):
        self.assertTrue(is_packaging(self._valid_setup_cfg_pkg()))

    def test_setup_cfg_and_invalid_setup_cfg_is_not_packaging_based(self):
        self.assertFalse(is_packaging(self._invalid_setup_cfg_pkg()))

    def test_get_install_method_with_setuptools_pkg(self):
        path = self._setuptools_setup_py_pkg()
        self.assertEqual("setuptools", get_install_method(path))

    def test_get_install_method_with_distutils_pkg(self):
        path = self._distutils_pkg_info()
        self.assertEqual("distutils", get_install_method(path))

    def test_get_install_method_with_packaging_pkg(self):
        path = self._valid_setup_cfg_pkg()
        self.assertEqual("distutils2", get_install_method(path))

    def test_get_install_method_with_unknown_pkg(self):
        path = self._invalid_setup_cfg_pkg()
        self.assertRaises(InstallationException, get_install_method, path)

    def test_is_setuptools_logs_setup_py_text_found(self):
        is_setuptools(self._setuptools_setup_py_pkg())
        expected = ['setup.py file found.',
                    'No egg-info directory found.',
                    'Found setuptools text in setup.py.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_setuptools_logs_setup_py_text_not_found(self):
        directory = self._random_setup_py_pkg()
        is_setuptools(directory)
        expected = ['setup.py file found.', 'No egg-info directory found.',
                    'No setuptools text found in setup.py.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_setuptools_logs_egg_info_dir_found(self):
        is_setuptools(self._setuptools_egg_info_pkg())
        expected = ['setup.py file found.', 'Found egg-info directory.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_distutils_logs_setup_py_text_found(self):
        is_distutils(self._distutils_setup_py_pkg())
        expected = ['setup.py file found.',
                    'No PKG-INFO file found.',
                    'Found distutils text in setup.py.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_distutils_logs_setup_py_text_not_found(self):
        directory = self._random_setup_py_pkg()
        is_distutils(directory)
        expected = ['setup.py file found.', 'No PKG-INFO file found.',
                    'No distutils text found in setup.py.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_distutils_logs_pkg_info_file_found(self):
        is_distutils(self._distutils_pkg_info())
        expected = ['setup.py file found.', 'PKG-INFO file found.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_packaging_logs_setup_cfg_found(self):
        is_packaging(self._valid_setup_cfg_pkg())
        expected = ['setup.cfg file found.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def test_is_packaging_logs_setup_cfg_not_found(self):
        is_packaging(self._empty_dir)
        expected = ['No setup.cfg file found.']
        self.assertEqual(expected, self.get_logs(logging.DEBUG))

    def _write_setuptools_setup_py(self, directory):
        self.write_file((directory, 'setup.py'),
                "from setuptools import setup")

    def _write_distutils_setup_py(self, directory):
        self.write_file([directory, 'setup.py'],
                "from distutils.core import setup")

    def _write_packaging_setup_cfg(self, directory):
        self.write_file([directory, 'setup.cfg'],
                        ("[metadata]\n"
                         "name = mypackage\n"
                         "version = 0.1.0\n"))

    def _setuptools_setup_py_pkg(self):
        tmp = self.mkdtemp()
        self._write_setuptools_setup_py(tmp)
        return tmp

    def _distutils_setup_py_pkg(self):
        tmp = self.mkdtemp()
        self._write_distutils_setup_py(tmp)
        return tmp

    def _valid_setup_cfg_pkg(self):
        tmp = self.mkdtemp()
        self._write_packaging_setup_cfg(tmp)
        return tmp

    def _setuptools_egg_info_pkg(self):
        tmp = self.mkdtemp()
        self._write_setuptools_setup_py(tmp)
        tempfile.mkdtemp(suffix='.egg-info', dir=tmp)
        return tmp

    def _distutils_pkg_info(self):
        tmp = self._distutils_setup_py_pkg()
        self.write_file([tmp, 'PKG-INFO'], '', encoding='UTF-8')
        return tmp

    def _setup_cfg_with_no_metadata_pkg(self):
        tmp = self.mkdtemp()
        self.write_file([tmp, 'setup.cfg'],
                        ("[othersection]\n"
                         "foo = bar\n"))
        return tmp

    def _invalid_setup_cfg_pkg(self):
        tmp = self.mkdtemp()
        self.write_file([tmp, 'setup.cfg'],
                        ("[metadata]\n"
                         "name = john\n"
                         "last_name = doe\n"))
        return tmp

    def _egg_info_with_no_setuptools(self):
        tmp = self._random_setup_py_pkg()
        tempfile.mkdtemp(suffix='.egg-info', dir=tmp)
        return tmp

    def _pkg_info_with_no_distutils(self):
        tmp = self._random_setup_py_pkg()
        self.write_file([tmp, 'PKG-INFO'], '', encoding='UTF-8')
        return tmp

    def _random_setup_py_pkg(self):
        tmp = self.mkdtemp()
        self.write_file((tmp, 'setup.py'), "from mypackage import setup")
        return tmp


def test_suite():
    suite = unittest.makeSuite(UtilTestCase)
    suite.addTest(unittest.makeSuite(GlobTestCase))
    suite.addTest(unittest.makeSuite(EggInfoToDistInfoTestCase))
    suite.addTest(unittest.makeSuite(PackagingLibChecks))
    return suite


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