-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
tests.py
1817 lines (1573 loc) · 66.4 KB
/
tests.py
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
import codecs
import locale
import os
import posixpath
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import unittest
import zipfile
from contextlib import closing
from functools import partial
from io import BytesIO, StringIO
from typing import Dict, Optional
from xml.etree import ElementTree as ET
if sys.version_info >= (3, 8):
from unittest import mock
else:
# unittest.mock in 3.7 is too old to support
# all the features used in the test suite
import mock
from check_manifest import rmtree
CAN_SKIP_TESTS = os.getenv('SKIP_NO_TESTS', '') == ''
try:
codecs.lookup('oem')
except LookupError:
HAS_OEM_CODEC = False
else:
# Python >= 3.6 on Windows
HAS_OEM_CODEC = True
class MockUI:
def __init__(self, verbosity=1):
self.verbosity = verbosity
self.warnings = []
self.errors = []
def info(self, message):
pass
def info_begin(self, message):
pass
def info_cont(self, message):
pass
def info_end(self, message):
pass
def warning(self, message):
self.warnings.append(message)
def error(self, message):
self.errors.append(message)
class Tests(unittest.TestCase):
def setUp(self):
self.ui = MockUI()
def make_temp_dir(self):
tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
self.addCleanup(rmtree, tmpdir)
return tmpdir
def create_file(self, filename, contents):
with open(filename, 'w') as f:
f.write(contents)
def create_zip_file(self, filename, filenames):
with closing(zipfile.ZipFile(filename, 'w')) as zf:
for fn in filenames:
zf.writestr(fn, '')
def create_tar_file(self, filename, filenames):
with closing(tarfile.TarFile(filename, 'w')) as tf:
for fn in filenames:
tf.addfile(tarfile.TarInfo(fn), BytesIO())
def test_run_success(self):
from check_manifest import run
self.assertEqual(run(["true"]), "")
def test_run_failure(self):
from check_manifest import CommandFailed, run
# /bin/false can return any non-zero status code, e.g. it returns 255
# on OpenIndiana: https://github.com/mgedmin/check-manifest/issues/162
command = [sys.executable, '-c', 'import sys; sys.exit(1)']
with self.assertRaises(CommandFailed) as cm:
run(command)
self.assertEqual(str(cm.exception),
f"{command!r} failed (status 1):\n")
def test_run_no_such_program(self):
from check_manifest import Failure, run
with self.assertRaises(Failure) as cm:
run(["there-is-really-no-such-program"])
# Linux says "[Errno 2] No such file or directory"
# Windows says "[Error 2] The system cannot find the file specified"
# but on 3.x it's "[WinErr 2] The system cannot find the file specified"
should_start_with = "could not run ['there-is-really-no-such-program']:"
self.assertTrue(
str(cm.exception).startswith(should_start_with),
'\n%r does not start with\n%r' % (str(cm.exception),
should_start_with))
def test_mkdtemp_readonly_files(self):
from check_manifest import mkdtemp
with mkdtemp(hint='-test-readonly') as d:
fn = os.path.join(d, 'file.txt')
with open(fn, 'w'):
pass
os.chmod(fn, 0o444) # readonly
assert not os.path.exists(d)
@unittest.skipIf(sys.platform == 'win32',
"No POSIX-like unreadable directories on Windows")
def test_rmtree_unreadable_directories(self):
d = self.make_temp_dir()
sd = os.path.join(d, 'subdir')
os.mkdir(sd)
os.chmod(sd, 0) # a bad mode for a directory, oops
# The onerror API of shutil.rmtree doesn't let us recover from
# os.listdir() failures.
with self.assertRaises(OSError):
rmtree(sd)
os.chmod(sd, 0o755) # so we can clean up
def test_rmtree_readonly_directories(self):
d = self.make_temp_dir()
sd = os.path.join(d, 'subdir')
fn = os.path.join(sd, 'file.txt')
os.mkdir(sd)
open(fn, 'w').close()
os.chmod(sd, 0o444) # a bad mode for a directory, oops
rmtree(sd)
assert not os.path.exists(sd)
def test_rmtree_readonly_directories_and_files(self):
d = self.make_temp_dir()
sd = os.path.join(d, 'subdir')
fn = os.path.join(sd, 'file.txt')
os.mkdir(sd)
open(fn, 'w').close()
os.chmod(fn, 0o444) # readonly
os.chmod(sd, 0o444) # a bad mode for a directory, oops
rmtree(sd)
assert not os.path.exists(sd)
def test_copy_files(self):
from check_manifest import copy_files
actions = []
n = os.path.normpath
with mock.patch('os.path.isdir', lambda d: d in ('b', n('/dest/dir'))):
with mock.patch('os.makedirs',
lambda d: actions.append('makedirs %s' % d)):
with mock.patch('os.mkdir',
lambda d: actions.append('mkdir %s' % d)):
with mock.patch('shutil.copy2',
lambda s, d: actions.append(f'cp {s} {d}')):
copy_files(['a', 'b', n('c/d/e')], n('/dest/dir'))
self.assertEqual(
actions,
[
'cp a %s' % n('/dest/dir/a'),
'mkdir %s' % n('/dest/dir/b'),
'makedirs %s' % n('/dest/dir/c/d'),
'cp %s %s' % (n('c/d/e'), n('/dest/dir/c/d/e')),
])
def test_get_one_file_in(self):
from check_manifest import get_one_file_in
with mock.patch('os.listdir', lambda dir: ['a']):
self.assertEqual(get_one_file_in(os.path.normpath('/some/dir')),
os.path.normpath('/some/dir/a'))
def test_get_one_file_in_empty_directory(self):
from check_manifest import Failure, get_one_file_in
with mock.patch('os.listdir', lambda dir: []):
with self.assertRaises(Failure) as cm:
get_one_file_in('/some/dir')
self.assertEqual(str(cm.exception),
"No files found in /some/dir")
def test_get_one_file_in_too_many(self):
from check_manifest import Failure, get_one_file_in
with mock.patch('os.listdir', lambda dir: ['b', 'a']):
with self.assertRaises(Failure) as cm:
get_one_file_in('/some/dir')
self.assertEqual(str(cm.exception),
"More than one file exists in /some/dir:\na\nb")
def test_unicodify(self):
from check_manifest import unicodify
nonascii = "\u00E9.txt"
self.assertEqual(unicodify(nonascii), nonascii)
self.assertEqual(
unicodify(nonascii.encode(locale.getpreferredencoding())),
nonascii)
def test_get_archive_file_list_unrecognized_archive(self):
from check_manifest import Failure, get_archive_file_list
with self.assertRaises(Failure) as cm:
get_archive_file_list('/path/to/archive.rar')
self.assertEqual(str(cm.exception),
'Unrecognized archive type: archive.rar')
def test_get_archive_file_list_zip(self):
from check_manifest import get_archive_file_list
filename = os.path.join(self.make_temp_dir(), 'archive.zip')
self.create_zip_file(filename, ['a', 'b/c'])
self.assertEqual(get_archive_file_list(filename),
['a', 'b/c'])
def test_get_archive_file_list_zip_nonascii(self):
from check_manifest import get_archive_file_list
filename = os.path.join(self.make_temp_dir(), 'archive.zip')
nonascii = "\u00E9.txt"
self.create_zip_file(filename, [nonascii])
self.assertEqual(get_archive_file_list(filename),
[nonascii])
def test_get_archive_file_list_tar(self):
from check_manifest import get_archive_file_list
filename = os.path.join(self.make_temp_dir(), 'archive.tar')
self.create_tar_file(filename, ['a', 'b/c'])
self.assertEqual(get_archive_file_list(filename),
['a', 'b/c'])
def test_get_archive_file_list_tar_nonascii(self):
from check_manifest import get_archive_file_list
filename = os.path.join(self.make_temp_dir(), 'archive.tar')
nonascii = "\u00E9.txt"
self.create_tar_file(filename, [nonascii])
self.assertEqual(get_archive_file_list(filename),
[nonascii])
def test_format_list(self):
from check_manifest import format_list
self.assertEqual(format_list([]), "")
self.assertEqual(format_list(['a']), " a")
self.assertEqual(format_list(['a', 'b']), " a\n b")
def test_format_missing(self):
from check_manifest import format_missing
self.assertEqual(
format_missing(set(), set(), "1st", "2nd"),
"")
self.assertEqual(
format_missing({"c"}, {"a"}, "1st", "2nd"),
"missing from 1st:\n"
" c\n"
"missing from 2nd:\n"
" a")
def test_strip_toplevel_name_empty_list(self):
from check_manifest import strip_toplevel_name
self.assertEqual(strip_toplevel_name([]), [])
def test_strip_toplevel_name_no_common_prefix(self):
from check_manifest import Failure, strip_toplevel_name
self.assertRaises(Failure, strip_toplevel_name, ["a/b", "c/d"])
def test_detect_vcs_no_vcs(self):
from check_manifest import Failure, detect_vcs
ui = MockUI()
with mock.patch('check_manifest.VCS.detect', staticmethod(lambda *a: False)):
with mock.patch('check_manifest.Git.detect', staticmethod(lambda *a: False)):
with self.assertRaises(Failure) as cm:
detect_vcs(ui)
self.assertEqual(str(cm.exception),
"Couldn't find version control data"
" (git/hg/bzr/svn supported)")
def test_normalize_names(self):
from check_manifest import normalize_names
j = os.path.join
self.assertEqual(normalize_names(["a", j("b", ""), j("c", "d"),
j("e", "f", ""),
j("g", "h", "..", "i")]),
["a", "b", "c/d", "e/f", "g/i"])
def test_canonical_file_list(self):
from check_manifest import canonical_file_list
j = os.path.join
self.assertEqual(
canonical_file_list(['b', 'a', 'c', j('c', 'd'), j('e', 'f'),
'g', j('g', 'h', 'i', 'j')]),
['a', 'b', 'c/d', 'e/f', 'g/h/i/j'])
def test_file_matches(self):
from check_manifest import file_matches
patterns = ['setup.cfg', '*.egg-info', '*.egg-info/*']
self.assertFalse(file_matches('setup.py', patterns))
self.assertTrue(file_matches('setup.cfg', patterns))
self.assertTrue(file_matches('src/zope.foo.egg-info', patterns))
self.assertTrue(file_matches('src/zope.foo.egg-info/SOURCES.txt',
patterns))
def test_strip_sdist_extras(self):
from check_manifest import (
IgnoreList,
canonical_file_list,
strip_sdist_extras,
)
filelist = canonical_file_list([
'.circleci/config.yml',
'.github',
'.github/ISSUE_TEMPLATE',
'.github/ISSUE_TEMPLATE/bug_report.md',
'.gitignore',
'.gitpod.yml',
'.travis.yml',
'setup.py',
'setup.cfg',
'README.txt',
'src',
'src/.gitignore',
'src/zope',
'src/zope/__init__.py',
'src/zope/foo',
'src/zope/foo/__init__.py',
'src/zope/foo/language.po',
'src/zope/foo/language.mo',
'src/zope.foo.egg-info',
'src/zope.foo.egg-info/SOURCES.txt',
])
expected = canonical_file_list([
'setup.py',
'README.txt',
'src',
'src/zope',
'src/zope/__init__.py',
'src/zope/foo',
'src/zope/foo/__init__.py',
'src/zope/foo/language.po',
])
ignore = IgnoreList.default()
self.assertEqual(strip_sdist_extras(ignore, filelist), expected)
def test_strip_sdist_extras_with_manifest(self):
from check_manifest import (
IgnoreList,
_get_ignore_from_manifest_lines,
canonical_file_list,
strip_sdist_extras,
)
manifest_in = textwrap.dedent("""
graft src
exclude *.cfg
global-exclude *.mo
prune src/dump
recursive-exclude src/zope *.sh
""")
filelist = canonical_file_list([
'.github/ISSUE_TEMPLATE/bug_report.md',
'.gitignore',
'setup.py',
'setup.cfg',
'MANIFEST.in',
'README.txt',
'src',
'src/helper.sh',
'src/dump',
'src/dump/__init__.py',
'src/zope',
'src/zope/__init__.py',
'src/zope/zopehelper.sh',
'src/zope/foo',
'src/zope/foo/__init__.py',
'src/zope/foo/language.po',
'src/zope/foo/language.mo',
'src/zope/foo/config.cfg',
'src/zope/foo/foohelper.sh',
'src/zope.foo.egg-info',
'src/zope.foo.egg-info/SOURCES.txt',
])
expected = canonical_file_list([
'setup.py',
'MANIFEST.in',
'README.txt',
'src',
'src/helper.sh',
'src/zope',
'src/zope/__init__.py',
'src/zope/foo',
'src/zope/foo/__init__.py',
'src/zope/foo/language.po',
'src/zope/foo/config.cfg',
])
ignore = IgnoreList.default()
ignore += _get_ignore_from_manifest_lines(manifest_in.splitlines(), self.ui)
result = strip_sdist_extras(ignore, filelist)
self.assertEqual(result, expected)
def test_find_bad_ideas(self):
from check_manifest import find_bad_ideas
filelist = [
'.gitignore',
'setup.py',
'setup.cfg',
'README.txt',
'src',
'src/zope',
'src/zope/__init__.py',
'src/zope/foo',
'src/zope/foo/__init__.py',
'src/zope/foo/language.po',
'src/zope/foo/language.mo',
'src/zope.foo.egg-info',
'src/zope.foo.egg-info/SOURCES.txt',
]
expected = [
'src/zope/foo/language.mo',
'src/zope.foo.egg-info',
]
self.assertEqual(find_bad_ideas(filelist), expected)
def test_find_suggestions(self):
from check_manifest import find_suggestions
self.assertEqual(find_suggestions(['buildout.cfg']),
(['include buildout.cfg'], []))
self.assertEqual(find_suggestions(['unknown.file~']),
([], ['unknown.file~']))
self.assertEqual(find_suggestions(['README.txt', 'CHANGES.txt']),
(['include *.txt'], []))
filelist = [
'docs/index.rst',
'docs/image.png',
'docs/Makefile',
'docs/unknown-file',
'src/etc/blah/blah/Makefile',
]
expected_rules = [
'recursive-include docs *.png',
'recursive-include docs *.rst',
'recursive-include docs Makefile',
'recursive-include src Makefile',
]
expected_unknowns = ['docs/unknown-file']
self.assertEqual(find_suggestions(filelist),
(expected_rules, expected_unknowns))
def test_find_suggestions_generic_fallback_rules(self):
from check_manifest import find_suggestions
self.assertEqual(find_suggestions(['Changelog']),
(['include Changelog'], []))
self.assertEqual(find_suggestions(['id-lang.map']),
(['include *.map'], []))
self.assertEqual(find_suggestions(['src/id-lang.map']),
(['recursive-include src *.map'], []))
def test_is_package(self):
from check_manifest import is_package
j = os.path.join
exists = {j('a', 'setup.py'), j('c', 'pyproject.toml')}
with mock.patch('os.path.exists', lambda fn: fn in exists):
self.assertTrue(is_package('a'))
self.assertFalse(is_package('b'))
self.assertTrue(is_package('c'))
def test_extract_version_from_filename(self):
from check_manifest import extract_version_from_filename as e
self.assertEqual(e('dist/foo_bar-1.2.3.dev4+g12345.zip'), '1.2.3.dev4+g12345')
self.assertEqual(e('dist/foo_bar-1.2.3.dev4+g12345.tar.gz'), '1.2.3.dev4+g12345')
self.assertEqual(e('dist/foo-bar-1.2.3.dev4+g12345.tar.gz'), '1.2.3.dev4+g12345')
def test_get_ignore_from_manifest_lines(self):
from check_manifest import IgnoreList, _get_ignore_from_manifest_lines
parse = partial(_get_ignore_from_manifest_lines, ui=self.ui)
self.assertEqual(parse([]),
IgnoreList())
self.assertEqual(parse(['', ' ']),
IgnoreList())
self.assertEqual(parse(['exclude *.cfg']),
IgnoreList().exclude('*.cfg'))
self.assertEqual(parse(['exclude *.cfg']),
IgnoreList().exclude('*.cfg'))
self.assertEqual(parse(['\texclude\t*.cfg foo.* bar.txt']),
IgnoreList().exclude('*.cfg', 'foo.*', 'bar.txt'))
self.assertEqual(parse(['exclude some/directory/*.cfg']),
IgnoreList().exclude('some/directory/*.cfg'))
self.assertEqual(parse(['include *.cfg']),
IgnoreList())
self.assertEqual(parse(['global-exclude *.pyc']),
IgnoreList().global_exclude('*.pyc'))
self.assertEqual(parse(['global-exclude *.pyc *.sh']),
IgnoreList().global_exclude('*.pyc', '*.sh'))
self.assertEqual(parse(['recursive-exclude dir *.pyc']),
IgnoreList().recursive_exclude('dir', '*.pyc'))
self.assertEqual(parse(['recursive-exclude dir *.pyc foo*.sh']),
IgnoreList().recursive_exclude('dir', '*.pyc', 'foo*.sh'))
self.assertEqual(parse(['recursive-exclude dir nopattern.xml']),
IgnoreList().recursive_exclude('dir', 'nopattern.xml'))
# We should not fail when a recursive-exclude line is wrong:
self.assertEqual(parse(['recursive-exclude dirwithoutpattern']),
IgnoreList())
self.assertEqual(parse(['prune dir']),
IgnoreList().prune('dir'))
# And a mongo test case of everything at the end
text = textwrap.dedent("""
exclude *.02
exclude *.03 04.* bar.txt
exclude *.05
exclude some/directory/*.cfg
global-exclude *.10 *.11
global-exclude *.12
include *.20
prune 30
recursive-exclude 40 *.41
recursive-exclude 42 *.43 44.*
""").splitlines()
self.assertEqual(
parse(text),
IgnoreList()
.exclude('*.02', '*.03', '04.*', 'bar.txt', '*.05', 'some/directory/*.cfg')
.global_exclude('*.10', '*.11', '*.12')
.prune('30')
.recursive_exclude('40', '*.41')
.recursive_exclude('42', '*.43', '44.*')
)
def test_get_ignore_from_manifest_lines_warns(self):
from check_manifest import IgnoreList, _get_ignore_from_manifest_lines
parse = partial(_get_ignore_from_manifest_lines, ui=self.ui)
text = textwrap.dedent("""
graft a/
recursive-include /b *.txt
""").splitlines()
self.assertEqual(parse(text), IgnoreList())
self.assertEqual(self.ui.warnings, [
'ERROR: Trailing slashes are not allowed in MANIFEST.in on Windows: a/',
'ERROR: Leading slashes are not allowed in MANIFEST.in on Windows: /b',
])
def test_get_ignore_from_manifest(self):
from check_manifest import IgnoreList, _get_ignore_from_manifest
filename = os.path.join(self.make_temp_dir(), 'MANIFEST.in')
self.create_file(filename, textwrap.dedent('''
exclude \\
# yes, this is allowed!
test.dat
# https://github.com/mgedmin/check-manifest/issues/66
# docs/ folder
'''))
ui = MockUI()
self.assertEqual(_get_ignore_from_manifest(filename, ui),
IgnoreList().exclude('test.dat'))
self.assertEqual(ui.warnings, [])
def test_get_ignore_from_manifest_warnings(self):
from check_manifest import IgnoreList, _get_ignore_from_manifest
filename = os.path.join(self.make_temp_dir(), 'MANIFEST.in')
self.create_file(filename, textwrap.dedent('''
# this is bad: a file should not end with a backslash
exclude test.dat \\
'''))
ui = MockUI()
self.assertEqual(_get_ignore_from_manifest(filename, ui),
IgnoreList().exclude('test.dat'))
self.assertEqual(ui.warnings, [
"%s, line 2: continuation line immediately precedes end-of-file" % filename,
])
def test_should_use_pep517_no_pyproject_toml(self):
from check_manifest import cd, should_use_pep_517
src_dir = self.make_temp_dir()
with cd(src_dir):
self.assertFalse(should_use_pep_517())
def test_should_use_pep517_no_build_system(self):
from check_manifest import cd, should_use_pep_517
src_dir = self.make_temp_dir()
filename = os.path.join(src_dir, 'pyproject.toml')
self.create_file(filename, textwrap.dedent('''
[tool.check-manifest]
'''))
with cd(src_dir):
self.assertFalse(should_use_pep_517())
def test_should_use_pep517_no_build_backend(self):
from check_manifest import cd, should_use_pep_517
src_dir = self.make_temp_dir()
filename = os.path.join(src_dir, 'pyproject.toml')
self.create_file(filename, textwrap.dedent('''
[build-system]
requires = [
"setuptools >= 40.6.0",
"wheel",
]
'''))
with cd(src_dir):
self.assertFalse(should_use_pep_517())
def test_should_use_pep517_yes_please(self):
from check_manifest import cd, should_use_pep_517
src_dir = self.make_temp_dir()
filename = os.path.join(src_dir, 'pyproject.toml')
self.create_file(filename, textwrap.dedent('''
[build-system]
requires = [
"setuptools >= 40.6.0",
"wheel",
]
build-backend = "setuptools.build_meta"
'''))
with cd(src_dir):
self.assertTrue(should_use_pep_517())
def _test_build_sdist_pep517(self, build_isolation):
from check_manifest import build_sdist, cd, get_one_file_in
src_dir = self.make_temp_dir()
filename = os.path.join(src_dir, 'pyproject.toml')
self.create_file(filename, textwrap.dedent('''
[build-system]
requires = [
"setuptools >= 40.6.0",
"wheel",
]
build-backend = "setuptools.build_meta"
'''))
out_dir = self.make_temp_dir()
python = os.path.abspath(sys.executable)
with cd(src_dir):
build_sdist(out_dir, python=python, build_isolation=build_isolation)
self.assertTrue(get_one_file_in(out_dir))
def test_build_sdist_pep517_isolated(self):
self._test_build_sdist_pep517(build_isolation=True)
def test_build_sdist_pep517_no_isolation(self):
self._test_build_sdist_pep517(build_isolation=False)
class TestConfiguration(unittest.TestCase):
def setUp(self):
self.oldpwd = os.getcwd()
self.tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
os.chdir(self.tmpdir)
self.ui = MockUI()
def tearDown(self):
os.chdir(self.oldpwd)
rmtree(self.tmpdir)
def test_read_config_no_config(self):
import check_manifest
ignore, ignore_bad_ideas = check_manifest.read_config()
self.assertEqual(ignore, check_manifest.IgnoreList.default())
def test_read_setup_config_no_section(self):
import check_manifest
with open('setup.cfg', 'w') as f:
f.write('[pep8]\nignore =\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
self.assertEqual(ignore, check_manifest.IgnoreList.default())
def test_read_pyproject_config_no_section(self):
import check_manifest
with open('pyproject.toml', 'w') as f:
f.write('[tool.pep8]\nignore = []\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
self.assertEqual(ignore, check_manifest.IgnoreList.default())
def test_read_setup_config_no_option(self):
import check_manifest
with open('setup.cfg', 'w') as f:
f.write('[check-manifest]\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
self.assertEqual(ignore, check_manifest.IgnoreList.default())
def test_read_pyproject_config_no_option(self):
import check_manifest
with open('pyproject.toml', 'w') as f:
f.write('[tool.check-manifest]\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
self.assertEqual(ignore, check_manifest.IgnoreList.default())
def test_read_setup_config_extra_ignores(self):
import check_manifest
with open('setup.cfg', 'w') as f:
f.write('[check-manifest]\nignore = foo\n bar*\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList.default().global_exclude('foo', 'bar*')
self.assertEqual(ignore, expected)
def test_read_pyproject_config_extra_ignores(self):
import check_manifest
with open('pyproject.toml', 'w') as f:
f.write('[tool.check-manifest]\nignore = ["foo", "bar*"]\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList.default().global_exclude('foo', 'bar*')
self.assertEqual(ignore, expected)
def test_read_setup_config_override_ignores(self):
import check_manifest
with open('setup.cfg', 'w') as f:
f.write('[check-manifest]\nignore = foo\n\n bar\n')
f.write('ignore-default-rules = yes\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList().global_exclude('foo', 'bar')
self.assertEqual(ignore, expected)
def test_read_pyproject_config_override_ignores(self):
import check_manifest
with open('pyproject.toml', 'w') as f:
f.write('[tool.check-manifest]\nignore = ["foo", "bar"]\n')
f.write('ignore-default-rules = true\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList().global_exclude('foo', 'bar')
self.assertEqual(ignore, expected)
def test_read_setup_config_ignore_bad_ideas(self):
import check_manifest
with open('setup.cfg', 'w') as f:
f.write('[check-manifest]\n'
'ignore-bad-ideas = \n'
' foo\n'
' bar*\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList().global_exclude('foo', 'bar*')
self.assertEqual(ignore_bad_ideas, expected)
def test_read_pyproject_config_ignore_bad_ideas(self):
import check_manifest
with open('pyproject.toml', 'w') as f:
f.write('[tool.check-manifest]\n'
'ignore-bad-ideas = ["foo", "bar*"]\n')
ignore, ignore_bad_ideas = check_manifest.read_config()
expected = check_manifest.IgnoreList().global_exclude('foo', 'bar*')
self.assertEqual(ignore_bad_ideas, expected)
def test_read_manifest_no_manifest(self):
import check_manifest
ignore = check_manifest.read_manifest(self.ui)
self.assertEqual(ignore, check_manifest.IgnoreList())
def test_read_manifest(self):
import check_manifest
from check_manifest import IgnoreList
with open('MANIFEST.in', 'w') as f:
f.write('exclude *.gif\n')
f.write('global-exclude *.png\n')
ignore = check_manifest.read_manifest(self.ui)
self.assertEqual(ignore, IgnoreList().exclude('*.gif').global_exclude('*.png'))
class TestMain(unittest.TestCase):
def setUp(self):
self._cm_patcher = mock.patch('check_manifest.check_manifest')
self._check_manifest = self._cm_patcher.start()
self._se_patcher = mock.patch('sys.exit')
self._sys_exit = self._se_patcher.start()
self.ui = MockUI()
self._ui_patcher = mock.patch('check_manifest.UI', self._make_ui)
self._ui_patcher.start()
self._orig_sys_argv = sys.argv
sys.argv = ['check-manifest']
def tearDown(self):
sys.argv = self._orig_sys_argv
self._se_patcher.stop()
self._cm_patcher.stop()
self._ui_patcher.stop()
def _make_ui(self, verbosity):
self.ui.verbosity = verbosity
return self.ui
def test(self):
from check_manifest import main
sys.argv.append('-v')
main()
def test_exit_code_1_on_error(self):
from check_manifest import main
self._check_manifest.return_value = False
main()
self._sys_exit.assert_called_with(1)
def test_exit_code_2_on_failure(self):
from check_manifest import Failure, main
self._check_manifest.side_effect = Failure('msg')
main()
self.assertEqual(self.ui.errors, ['msg'])
self._sys_exit.assert_called_with(2)
def test_extra_ignore_args(self):
import check_manifest
sys.argv.append('--ignore=x,y,z*')
check_manifest.main()
ignore = check_manifest.IgnoreList().global_exclude('x', 'y', 'z*')
self.assertEqual(self._check_manifest.call_args.kwargs['extra_ignore'],
ignore)
def test_ignore_bad_ideas_args(self):
import check_manifest
sys.argv.append('--ignore-bad-ideas=x,y,z*')
check_manifest.main()
ignore = check_manifest.IgnoreList().global_exclude('x', 'y', 'z*')
self.assertEqual(self._check_manifest.call_args.kwargs['extra_ignore_bad_ideas'],
ignore)
def test_verbose_arg(self):
import check_manifest
sys.argv.append('--verbose')
check_manifest.main()
self.assertEqual(self.ui.verbosity, 2)
def test_quiet_arg(self):
import check_manifest
sys.argv.append('--quiet')
check_manifest.main()
self.assertEqual(self.ui.verbosity, 0)
def test_verbose_and_quiet_arg(self):
import check_manifest
sys.argv.append('--verbose')
sys.argv.append('--quiet')
check_manifest.main()
# the two arguments cancel each other out:
# 1 (default verbosity) + 1 - 1 = 1.
self.assertEqual(self.ui.verbosity, 1)
class TestZestIntegration(unittest.TestCase):
def setUp(self):
sys.modules['zest'] = mock.Mock()
sys.modules['zest.releaser'] = mock.Mock()
sys.modules['zest.releaser.utils'] = mock.Mock()
self.ask = sys.modules['zest.releaser.utils'].ask
self.ui = MockUI()
self._ui_patcher = mock.patch('check_manifest.UI', return_value=self.ui)
self._ui_patcher.start()
def tearDown(self):
self._ui_patcher.stop()
del sys.modules['zest.releaser.utils']
del sys.modules['zest.releaser']
del sys.modules['zest']
@mock.patch('check_manifest.is_package', lambda d: False)
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_not_a_package(self, check_manifest):
from check_manifest import zest_releaser_check
zest_releaser_check(dict(workingdir='.'))
check_manifest.assert_not_called()
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_user_disagrees(self, check_manifest):
from check_manifest import zest_releaser_check
self.ask.return_value = False
zest_releaser_check(dict(workingdir='.'))
check_manifest.assert_not_called()
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('sys.exit')
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_all_okay(self, check_manifest, sys_exit):
from check_manifest import zest_releaser_check
self.ask.return_value = True
check_manifest.return_value = True
zest_releaser_check(dict(workingdir='.'))
sys_exit.assert_not_called()
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('sys.exit')
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_error_user_aborts(self, check_manifest,
sys_exit):
from check_manifest import zest_releaser_check
self.ask.side_effect = [True, False]
check_manifest.return_value = False
zest_releaser_check(dict(workingdir='.'))
sys_exit.assert_called_with(1)
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('sys.exit')
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_error_user_plods_on(self, check_manifest,
sys_exit):
from check_manifest import zest_releaser_check
self.ask.side_effect = [True, True]
check_manifest.return_value = False
zest_releaser_check(dict(workingdir='.'))
sys_exit.assert_not_called()
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('sys.exit')
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_failure_user_aborts(self, check_manifest,
sys_exit):
from check_manifest import Failure, zest_releaser_check
self.ask.side_effect = [True, False]
check_manifest.side_effect = Failure('msg')
zest_releaser_check(dict(workingdir='.'))
self.assertEqual(self.ui.errors, ['msg'])
sys_exit.assert_called_with(2)
@mock.patch('check_manifest.is_package', lambda d: True)
@mock.patch('sys.exit')
@mock.patch('check_manifest.check_manifest')
def test_zest_releaser_check_failure_user_plods_on(self, check_manifest,
sys_exit):
from check_manifest import Failure, zest_releaser_check
self.ask.side_effect = [True, True]
check_manifest.side_effect = Failure('msg')
zest_releaser_check(dict(workingdir='.'))
self.assertEqual(self.ui.errors, ['msg'])
sys_exit.assert_not_called()
class VCSHelper:
# override in subclasses
command: Optional[str] = None
extra_env: Dict[str, str] = {}
@property
def version(self):
if not hasattr(self, '_version'):
if not self.is_installed():
self._version = None
return self._version
@property
def version_tuple(self):
return tuple(map(int, re.findall(r'\d+', self.version)))
def is_installed(self):
try:
p = subprocess.Popen([self.command, '--version'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = p.communicate()
self._version = stdout.decode('ascii', 'backslashreplace').strip()
rc = p.wait()
return (rc == 0)
except OSError:
return False
def _run(self, *command):
# Windows doesn't like Unicode arguments to subprocess.Popen(), on Py2:
# https://github.com/mgedmin/check-manifest/issues/23#issuecomment-33933031
if str is bytes:
command = [s.encode(locale.getpreferredencoding()) for s in command]
print('$', ' '.join(command))
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env={**os.environ, **self.extra_env})
stdout, stderr = p.communicate()
rc = p.wait()
if stdout:
print(stdout.decode('ascii', 'backslashreplace'))
if rc:
raise subprocess.CalledProcessError(rc, command[0], output=stdout)
class VCSMixin:
def setUp(self):
if not self.vcs.is_installed() and CAN_SKIP_TESTS:
self.skipTest("%s is not installed" % self.vcs.command)
self.tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
self.olddir = os.getcwd()
os.chdir(self.tmpdir)
self.ui = MockUI()
def tearDown(self):
os.chdir(self.olddir)
rmtree(self.tmpdir)
def _create_file(self, filename):
assert not os.path.isabs(filename)
basedir = os.path.dirname(filename)
if basedir and not os.path.isdir(basedir):
os.makedirs(basedir)
open(filename, 'w').close()
def _create_files(self, filenames):
for filename in filenames:
self._create_file(filename)