Debian Codegraph @

tests.py

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 import codecs
2 import locale
3 import os
4 import posixpath
5 import re
6 import shutil
7 import subprocess
8 import sys
9 import tarfile
10 import tempfile
11 import textwrap
12 import unittest
13 import zipfile
14 from contextlib import closing
15 from functools import partial
16 from io import BytesIO, StringIO
17 from typing import Dict, Optional
18 from unittest import mock
19 from xml.etree import ElementTree as ET
20
21 from check_manifest import rmtree
22
23
24 CAN_SKIP_TESTS = os.getenv('SKIP_NO_TESTS', '') == ''
25
26
27 try:
28 codecs.lookup('oem')
29 except LookupError:
30 HAS_OEM_CODEC = False
31 else:
32 # Python >= 3.6 on Windows
33 HAS_OEM_CODEC = True
34
35
36 class MockUI:
37
38 def __init__(self, verbosity=1):
39 self.verbosity = verbosity
40 self.warnings = []
41 self.errors = []
42
43 def info(self, message):
44 pass
45
46 def info_begin(self, message):
47 pass
48
49 def info_cont(self, message):
50 pass
51
52 def info_end(self, message):
53 pass
54
55 def warning(self, message):
56 self.warnings.append(message)
57
58 def error(self, message):
59 self.errors.append(message)
60
61
62 class Tests(unittest.TestCase):
63
64 def setUp(self):
65 self.ui = MockUI()
66
67 def make_temp_dir(self):
68 tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
69 self.addCleanup(rmtree, tmpdir)
70 return tmpdir
71
72 def create_file(self, filename, contents):
73 with open(filename, 'w') as f:
74 f.write(contents)
75
76 def create_zip_file(self, filename, filenames):
77 with closing(zipfile.ZipFile(filename, 'w')) as zf:
78 for fn in filenames:
79 zf.writestr(fn, '')
80
81 def create_tar_file(self, filename, filenames):
82 with closing(tarfile.TarFile(filename, 'w')) as tf:
83 for fn in filenames:
84 tf.addfile(tarfile.TarInfo(fn), BytesIO())
85
86 def test_run_success(self):
87 from check_manifest import run
88 self.assertEqual(run(["true"]), "")
89
90 def test_run_failure(self):
91 from check_manifest import CommandFailed, run
92
93 # /bin/false can return any non-zero status code, e.g. it returns 255
94 # on OpenIndiana: https://github.com/mgedmin/check-manifest/issues/162
95 command = [sys.executable, '-c', 'import sys; sys.exit(1)']
96 with self.assertRaises(CommandFailed) as cm:
97 run(command)
98 self.assertEqual(str(cm.exception),
99 f"{command!r} failed (status 1):\n")
100
101 def test_run_no_such_program(self):
102 from check_manifest import Failure, run
103 with self.assertRaises(Failure) as cm:
104 run(["there-is-really-no-such-program"])
105 # Linux says "[Errno 2] No such file or directory"
106 # Windows says "[Error 2] The system cannot find the file specified"
107 # but on 3.x it's "[WinErr 2] The system cannot find the file specified"
108 should_start_with = "could not run ['there-is-really-no-such-program']:"
109 self.assertTrue(
110 str(cm.exception).startswith(should_start_with),
111 '\n%r does not start with\n%r' % (str(cm.exception),
112 should_start_with))
113
114 def test_mkdtemp_readonly_files(self):
115 from check_manifest import mkdtemp
116 with mkdtemp(hint='-test-readonly') as d:
117 fn = os.path.join(d, 'file.txt')
118 with open(fn, 'w'):
119 pass
120 os.chmod(fn, 0o444) # readonly
121 assert not os.path.exists(d)
122
123 @unittest.skipIf(sys.platform == 'win32',
124 "No POSIX-like unreadable directories on Windows")
125 def test_rmtree_unreadable_directories(self):
126 d = self.make_temp_dir()
127 sd = os.path.join(d, 'subdir')
128 os.mkdir(sd)
129 os.chmod(sd, 0) # a bad mode for a directory, oops
130 # The onerror API of shutil.rmtree doesn't let us recover from
131 # os.listdir() failures.
132 with self.assertRaises(OSError):
133 rmtree(sd)
134 os.chmod(sd, 0o755) # so we can clean up
135
136 def test_rmtree_readonly_directories(self):
137 d = self.make_temp_dir()
138 sd = os.path.join(d, 'subdir')
139 fn = os.path.join(sd, 'file.txt')
140 os.mkdir(sd)
141 open(fn, 'w').close()
142 os.chmod(sd, 0o444) # a bad mode for a directory, oops
143 rmtree(sd)
144 assert not os.path.exists(sd)
145
146 def test_rmtree_readonly_directories_and_files(self):
147 d = self.make_temp_dir()
148 sd = os.path.join(d, 'subdir')
149 fn = os.path.join(sd, 'file.txt')
150 os.mkdir(sd)
151 open(fn, 'w').close()
152 os.chmod(fn, 0o444) # readonly
153 os.chmod(sd, 0o444) # a bad mode for a directory, oops
154 rmtree(sd)
155 assert not os.path.exists(sd)
156
157 def test_copy_files(self):
158 from check_manifest import copy_files
159 actions = []
160 n = os.path.normpath
161 with mock.patch('os.path.isdir', lambda d: d in ('b', n('/dest/dir'))):
162 with mock.patch('os.makedirs',
163 lambda d: actions.append('makedirs %s' % d)):
164 with mock.patch('os.mkdir',
165 lambda d: actions.append('mkdir %s' % d)):
166 with mock.patch('shutil.copy2',
167 lambda s, d: actions.append(f'cp {s} {d}')):
168 copy_files(['a', 'b', n('c/d/e')], n('/dest/dir'))
169 self.assertEqual(
170 actions,
171 [
172 'cp a %s' % n('/dest/dir/a'),
173 'mkdir %s' % n('/dest/dir/b'),
174 'makedirs %s' % n('/dest/dir/c/d'),
175 'cp %s %s' % (n('c/d/e'), n('/dest/dir/c/d/e')),
176 ])
177
178 def test_get_one_file_in(self):
179 from check_manifest import get_one_file_in
180 with mock.patch('os.listdir', lambda dir: ['a']):
181 self.assertEqual(get_one_file_in(os.path.normpath('/some/dir')),
182 os.path.normpath('/some/dir/a'))
183
184 def test_get_one_file_in_empty_directory(self):
185 from check_manifest import Failure, get_one_file_in
186 with mock.patch('os.listdir', lambda dir: []):
187 with self.assertRaises(Failure) as cm:
188 get_one_file_in('/some/dir')
189 self.assertEqual(str(cm.exception),
190 "No files found in /some/dir")
191
192 def test_get_one_file_in_too_many(self):
193 from check_manifest import Failure, get_one_file_in
194 with mock.patch('os.listdir', lambda dir: ['b', 'a']):
195 with self.assertRaises(Failure) as cm:
196 get_one_file_in('/some/dir')
197 self.assertEqual(str(cm.exception),
198 "More than one file exists in /some/dir:\na\nb")
199
200 def test_unicodify(self):
201 from check_manifest import unicodify
202 nonascii = "\u00E9.txt"
203 self.assertEqual(unicodify(nonascii), nonascii)
204 self.assertEqual(
205 unicodify(nonascii.encode(locale.getpreferredencoding())),
206 nonascii)
207
208 def test_get_archive_file_list_unrecognized_archive(self):
209 from check_manifest import Failure, get_archive_file_list
210 with self.assertRaises(Failure) as cm:
211 get_archive_file_list('/path/to/archive.rar')
212 self.assertEqual(str(cm.exception),
213 'Unrecognized archive type: archive.rar')
214
215 def test_get_archive_file_list_zip(self):
216 from check_manifest import get_archive_file_list
217 filename = os.path.join(self.make_temp_dir(), 'archive.zip')
218 self.create_zip_file(filename, ['a', 'b/c'])
219 self.assertEqual(get_archive_file_list(filename),
220 ['a', 'b/c'])
221
222 def test_get_archive_file_list_zip_nonascii(self):
223 from check_manifest import get_archive_file_list
224 filename = os.path.join(self.make_temp_dir(), 'archive.zip')
225 nonascii = "\u00E9.txt"
226 self.create_zip_file(filename, [nonascii])
227 self.assertEqual(get_archive_file_list(filename),
228 [nonascii])
229
230 def test_get_archive_file_list_tar(self):
231 from check_manifest import get_archive_file_list
232 filename = os.path.join(self.make_temp_dir(), 'archive.tar')
233 self.create_tar_file(filename, ['a', 'b/c'])
234 self.assertEqual(get_archive_file_list(filename),
235 ['a', 'b/c'])
236
237 def test_get_archive_file_list_tar_nonascii(self):
238 from check_manifest import get_archive_file_list
239 filename = os.path.join(self.make_temp_dir(), 'archive.tar')
240 nonascii = "\u00E9.txt"
241 self.create_tar_file(filename, [nonascii])
242 self.assertEqual(get_archive_file_list(filename),
243 [nonascii])
244
245 def test_format_list(self):
246 from check_manifest import format_list
247 self.assertEqual(format_list([]), "")
248 self.assertEqual(format_list(['a']), " a")
249 self.assertEqual(format_list(['a', 'b']), " a\n b")
250
251 def test_format_missing(self):
252 from check_manifest import format_missing
253 self.assertEqual(
254 format_missing(set(), set(), "1st", "2nd"),
255 "")
256 self.assertEqual(
257 format_missing({"c"}, {"a"}, "1st", "2nd"),
258 "missing from 1st:\n"
259 " c\n"
260 "missing from 2nd:\n"
261 " a")
262
263 def test_strip_toplevel_name_empty_list(self):
264 from check_manifest import strip_toplevel_name
265 self.assertEqual(strip_toplevel_name([]), [])
266
267 def test_strip_toplevel_name_no_common_prefix(self):
268 from check_manifest import Failure, strip_toplevel_name
269 self.assertRaises(Failure, strip_toplevel_name, ["a/b", "c/d"])
270
271 def test_detect_vcs_no_vcs(self):
272 from check_manifest import Failure, detect_vcs
273 ui = MockUI()
274 with mock.patch('check_manifest.VCS.detect', staticmethod(lambda *a: False)):
275 with mock.patch('check_manifest.Git.detect', staticmethod(lambda *a: False)):
276 with self.assertRaises(Failure) as cm:
277 detect_vcs(ui)
278 self.assertEqual(str(cm.exception),
279 "Couldn't find version control data"
280 " (git/hg/bzr/svn supported)")
281
282 def test_normalize_names(self):
283 from check_manifest import normalize_names
284 j = os.path.join
285 self.assertEqual(normalize_names(["a", j("b", ""), j("c", "d"),
286 j("e", "f", ""),
287 j("g", "h", "..", "i")]),
288 ["a", "b", "c/d", "e/f", "g/i"])
289
290 def test_canonical_file_list(self):
291 from check_manifest import canonical_file_list
292 j = os.path.join
293 self.assertEqual(
294 canonical_file_list(['b', 'a', 'c', j('c', 'd'), j('e', 'f'),
295 'g', j('g', 'h', 'i', 'j')]),
296 ['a', 'b', 'c/d', 'e/f', 'g/h/i/j'])
297
298 def test_file_matches(self):
299 from check_manifest import file_matches
300 patterns = ['setup.cfg', '*.egg-info', '*.egg-info/*']
301 self.assertFalse(file_matches('setup.py', patterns))
302 self.assertTrue(file_matches('setup.cfg', patterns))
303 self.assertTrue(file_matches('src/zope.foo.egg-info', patterns))
304 self.assertTrue(file_matches('src/zope.foo.egg-info/SOURCES.txt',
305 patterns))
306
307 def test_strip_sdist_extras(self):
308 from check_manifest import (
309 IgnoreList,
310 canonical_file_list,
311 strip_sdist_extras,
312 )
313 filelist = canonical_file_list([
314 '.circleci/config.yml',
315 '.github',
316 '.github/ISSUE_TEMPLATE',
317 '.github/ISSUE_TEMPLATE/bug_report.md',
318 '.gitignore',
319 '.gitpod.yml',
320 '.travis.yml',
321 'setup.py',
322 'setup.cfg',
323 'README.txt',
324 'src',
325 'src/.gitignore',
326 'src/zope',
327 'src/zope/__init__.py',
328 'src/zope/foo',
329 'src/zope/foo/__init__.py',
330 'src/zope/foo/language.po',
331 'src/zope/foo/language.mo',
332 'src/zope.foo.egg-info',
333 'src/zope.foo.egg-info/SOURCES.txt',
334 ])
335 expected = canonical_file_list([
336 'setup.py',
337 'README.txt',
338 'src',
339 'src/zope',
340 'src/zope/__init__.py',
341 'src/zope/foo',
342 'src/zope/foo/__init__.py',
343 'src/zope/foo/language.po',
344 ])
345 ignore = IgnoreList.default()
346 self.assertEqual(strip_sdist_extras(ignore, filelist), expected)
347
348 def test_strip_sdist_extras_with_manifest(self):
349 from check_manifest import (
350 IgnoreList,
351 _get_ignore_from_manifest_lines,
352 canonical_file_list,
353 strip_sdist_extras,
354 )
355 manifest_in = textwrap.dedent("""
356 graft src
357 exclude *.cfg
358 global-exclude *.mo
359 prune src/dump
360 recursive-exclude src/zope *.sh
361 """)
362 filelist = canonical_file_list([
363 '.github/ISSUE_TEMPLATE/bug_report.md',
364 '.gitignore',
365 'setup.py',
366 'setup.cfg',
367 'MANIFEST.in',
368 'README.txt',
369 'src',
370 'src/helper.sh',
371 'src/dump',
372 'src/dump/__init__.py',
373 'src/zope',
374 'src/zope/__init__.py',
375 'src/zope/zopehelper.sh',
376 'src/zope/foo',
377 'src/zope/foo/__init__.py',
378 'src/zope/foo/language.po',
379 'src/zope/foo/language.mo',
380 'src/zope/foo/config.cfg',
381 'src/zope/foo/foohelper.sh',
382 'src/zope.foo.egg-info',
383 'src/zope.foo.egg-info/SOURCES.txt',
384 ])
385 expected = canonical_file_list([
386 'setup.py',
387 'MANIFEST.in',
388 'README.txt',
389 'src',
390 'src/helper.sh',
391 'src/zope',
392 'src/zope/__init__.py',
393 'src/zope/foo',
394 'src/zope/foo/__init__.py',
395 'src/zope/foo/language.po',
396 'src/zope/foo/config.cfg',
397 ])
398 ignore = IgnoreList.default()
399 ignore += _get_ignore_from_manifest_lines(manifest_in.splitlines(), self.ui)
400 result = strip_sdist_extras(ignore, filelist)
401 self.assertEqual(result, expected)
402
403 def test_find_bad_ideas(self):
404 from check_manifest import find_bad_ideas
405 filelist = [
406 '.gitignore',
407 'setup.py',
408 'setup.cfg',
409 'README.txt',
410 'src',
411 'src/zope',
412 'src/zope/__init__.py',
413 'src/zope/foo',
414 'src/zope/foo/__init__.py',
415 'src/zope/foo/language.po',
416 'src/zope/foo/language.mo',
417 'src/zope.foo.egg-info',
418 'src/zope.foo.egg-info/SOURCES.txt',
419 ]
420 expected = [
421 'src/zope/foo/language.mo',
422 'src/zope.foo.egg-info',
423 ]
424 self.assertEqual(find_bad_ideas(filelist), expected)
425
426 def test_find_suggestions(self):
427 from check_manifest import find_suggestions
428 self.assertEqual(find_suggestions(['buildout.cfg']),
429 (['include buildout.cfg'], []))
430 self.assertEqual(find_suggestions(['unknown.file~']),
431 ([], ['unknown.file~']))
432 self.assertEqual(find_suggestions(['README.txt', 'CHANGES.txt']),
433 (['include *.txt'], []))
434 filelist = [
435 'docs/index.rst',
436 'docs/image.png',
437 'docs/Makefile',
438 'docs/unknown-file',
439 'src/etc/blah/blah/Makefile',
440 ]
441 expected_rules = [
442 'recursive-include docs *.png',
443 'recursive-include docs *.rst',
444 'recursive-include docs Makefile',
445 'recursive-include src Makefile',
446 ]
447 expected_unknowns = ['docs/unknown-file']
448 self.assertEqual(find_suggestions(filelist),
449 (expected_rules, expected_unknowns))
450
451 def test_find_suggestions_generic_fallback_rules(self):
452 from check_manifest import find_suggestions
453 self.assertEqual(find_suggestions(['Changelog']),
454 (['include Changelog'], []))
455 self.assertEqual(find_suggestions(['id-lang.map']),
456 (['include *.map'], []))
457 self.assertEqual(find_suggestions(['src/id-lang.map']),
458 (['recursive-include src *.map'], []))
459
460 def test_is_package(self):
461 from check_manifest import is_package
462 j = os.path.join
463 exists = {j('a', 'setup.py'), j('c', 'pyproject.toml')}
464 with mock.patch('os.path.exists', lambda fn: fn in exists):
465 self.assertTrue(is_package('a'))
466 self.assertFalse(is_package('b'))
467 self.assertTrue(is_package('c'))
468
469 def test_extract_version_from_filename(self):
470 from check_manifest import extract_version_from_filename as e
471 self.assertEqual(e('dist/foo_bar-1.2.3.dev4+g12345.zip'), '1.2.3.dev4+g12345')
472 self.assertEqual(e('dist/foo_bar-1.2.3.dev4+g12345.tar.gz'), '1.2.3.dev4+g12345')
473 self.assertEqual(e('dist/foo-bar-1.2.3.dev4+g12345.tar.gz'), '1.2.3.dev4+g12345')
474
475 def test_get_ignore_from_manifest_lines(self):
476 from check_manifest import IgnoreList, _get_ignore_from_manifest_lines
477 parse = partial(_get_ignore_from_manifest_lines, ui=self.ui)
478 self.assertEqual(parse([]),
479 IgnoreList())
480 self.assertEqual(parse(['', ' ']),
481 IgnoreList())
482 self.assertEqual(parse(['exclude *.cfg']),
483 IgnoreList().exclude('*.cfg'))
484 self.assertEqual(parse(['exclude *.cfg']),
485 IgnoreList().exclude('*.cfg'))
486 self.assertEqual(parse(['\texclude\t*.cfg foo.* bar.txt']),
487 IgnoreList().exclude('*.cfg', 'foo.*', 'bar.txt'))
488 self.assertEqual(parse(['exclude some/directory/*.cfg']),
489 IgnoreList().exclude('some/directory/*.cfg'))
490 self.assertEqual(parse(['include *.cfg']),
491 IgnoreList())
492 self.assertEqual(parse(['global-exclude *.pyc']),
493 IgnoreList().global_exclude('*.pyc'))
494 self.assertEqual(parse(['global-exclude *.pyc *.sh']),
495 IgnoreList().global_exclude('*.pyc', '*.sh'))
496 self.assertEqual(parse(['recursive-exclude dir *.pyc']),
497 IgnoreList().recursive_exclude('dir', '*.pyc'))
498 self.assertEqual(parse(['recursive-exclude dir *.pyc foo*.sh']),
499 IgnoreList().recursive_exclude('dir', '*.pyc', 'foo*.sh'))
500 self.assertEqual(parse(['recursive-exclude dir nopattern.xml']),
501 IgnoreList().recursive_exclude('dir', 'nopattern.xml'))
502 # We should not fail when a recursive-exclude line is wrong:
503 self.assertEqual(parse(['recursive-exclude dirwithoutpattern']),
504 IgnoreList())
505 self.assertEqual(parse(['prune dir']),
506 IgnoreList().prune('dir'))
507 # And a mongo test case of everything at the end
508 text = textwrap.dedent("""
509 exclude *.02
510 exclude *.03 04.* bar.txt
511 exclude *.05
512 exclude some/directory/*.cfg
513 global-exclude *.10 *.11
514 global-exclude *.12
515 include *.20
516 prune 30
517 recursive-exclude 40 *.41
518 recursive-exclude 42 *.43 44.*
519 """).splitlines()
520 self.assertEqual(
521 parse(text),
522 IgnoreList()
523 .exclude('*.02', '*.03', '04.*', 'bar.txt', '*.05', 'some/directory/*.cfg')
524 .global_exclude('*.10', '*.11', '*.12')
525 .prune('30')
526 .recursive_exclude('40', '*.41')
527 .recursive_exclude('42', '*.43', '44.*')
528 )
529
530 def test_get_ignore_from_manifest_lines_warns(self):
531 from check_manifest import IgnoreList, _get_ignore_from_manifest_lines
532 parse = partial(_get_ignore_from_manifest_lines, ui=self.ui)
533 text = textwrap.dedent("""
534 graft a/
535 recursive-include /b *.txt
536 """).splitlines()
537 self.assertEqual(parse(text), IgnoreList())
538 self.assertEqual(self.ui.warnings, [
539 'ERROR: Trailing slashes are not allowed in MANIFEST.in on Windows: a/',
540 'ERROR: Leading slashes are not allowed in MANIFEST.in on Windows: /b',
541 ])
542
543 def test_get_ignore_from_manifest(self):
544 from check_manifest import IgnoreList, _get_ignore_from_manifest
545 filename = os.path.join(self.make_temp_dir(), 'MANIFEST.in')
546 self.create_file(filename, textwrap.dedent('''
547 exclude \\
548 # yes, this is allowed!
549 test.dat
550
551 # https://github.com/mgedmin/check-manifest/issues/66
552 # docs/ folder
553 '''))
554 ui = MockUI()
555 self.assertEqual(_get_ignore_from_manifest(filename, ui),
556 IgnoreList().exclude('test.dat'))
557 self.assertEqual(ui.warnings, [])
558
559 def test_get_ignore_from_manifest_warnings(self):
560 from check_manifest import IgnoreList, _get_ignore_from_manifest
561 filename = os.path.join(self.make_temp_dir(), 'MANIFEST.in')
562 self.create_file(filename, textwrap.dedent('''
563 # this is bad: a file should not end with a backslash
564 exclude test.dat \\
565 '''))
566 ui = MockUI()
567 self.assertEqual(_get_ignore_from_manifest(filename, ui),
568 IgnoreList().exclude('test.dat'))
569 self.assertEqual(ui.warnings, [
570 "%s, line 2: continuation line immediately precedes end-of-file" % filename,
571 ])
572
573 def test_should_use_pep517_no_pyproject_toml(self):
574 from check_manifest import cd, should_use_pep_517
575 src_dir = self.make_temp_dir()
576 with cd(src_dir):
577 self.assertFalse(should_use_pep_517())
578
579 def test_should_use_pep517_no_build_system(self):
580 from check_manifest import cd, should_use_pep_517
581 src_dir = self.make_temp_dir()
582 filename = os.path.join(src_dir, 'pyproject.toml')
583 self.create_file(filename, textwrap.dedent('''
584 [tool.check-manifest]
585 '''))
586 with cd(src_dir):
587 self.assertFalse(should_use_pep_517())
588
589 def test_should_use_pep517_no_build_backend(self):
590 from check_manifest import cd, should_use_pep_517
591 src_dir = self.make_temp_dir()
592 filename = os.path.join(src_dir, 'pyproject.toml')
593 self.create_file(filename, textwrap.dedent('''
594 [build-system]
595 requires = [
596 "setuptools >= 40.6.0",
597 "wheel",
598 ]
599 '''))
600 with cd(src_dir):
601 self.assertFalse(should_use_pep_517())
602
603 def test_should_use_pep517_yes_please(self):
604 from check_manifest import cd, should_use_pep_517
605 src_dir = self.make_temp_dir()
606 filename = os.path.join(src_dir, 'pyproject.toml')
607 self.create_file(filename, textwrap.dedent('''
608 [build-system]
609 requires = [
610 "setuptools >= 40.6.0",
611 "wheel",
612 ]
613 build-backend = "setuptools.build_meta"
614 '''))
615 with cd(src_dir):
616 self.assertTrue(should_use_pep_517())
617
618 def _test_build_sdist_pep517(self, build_isolation):
619 from check_manifest import build_sdist, cd, get_one_file_in
620 src_dir = self.make_temp_dir()
621 filename = os.path.join(src_dir, 'pyproject.toml')
622 self.create_file(filename, textwrap.dedent('''
623 [build-system]
624 requires = [
625 "setuptools >= 40.6.0",
626 "wheel",
627 ]
628 build-backend = "setuptools.build_meta"
629 '''))
630 out_dir = self.make_temp_dir()
631 python = os.path.abspath(sys.executable)
632 with cd(src_dir):
633 build_sdist(out_dir, python=python, build_isolation=build_isolation)
634 self.assertTrue(get_one_file_in(out_dir))
635
636 def test_build_sdist_pep517_isolated(self):
637 self._test_build_sdist_pep517(build_isolation=True)
638
639 def test_build_sdist_pep517_no_isolation(self):
640 self._test_build_sdist_pep517(build_isolation=False)
641
642
643 class TestConfiguration(unittest.TestCase):
644
645 def setUp(self):
646 self.oldpwd = os.getcwd()
647 self.tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
648 os.chdir(self.tmpdir)
649 self.ui = MockUI()
650
651 def tearDown(self):
652 os.chdir(self.oldpwd)
653 rmtree(self.tmpdir)
654
655 def test_read_config_no_config(self):
656 import check_manifest
657 ignore, ignore_bad_ideas = check_manifest.read_config()
658 self.assertEqual(ignore, check_manifest.IgnoreList.default())
659
660 def test_read_setup_config_no_section(self):
661 import check_manifest
662 with open('setup.cfg', 'w') as f:
663 f.write('[pep8]\nignore =\n')
664 ignore, ignore_bad_ideas = check_manifest.read_config()
665 self.assertEqual(ignore, check_manifest.IgnoreList.default())
666
667 def test_read_pyproject_config_no_section(self):
668 import check_manifest
669 with open('pyproject.toml', 'w') as f:
670 f.write('[tool.pep8]\nignore = []\n')
671 ignore, ignore_bad_ideas = check_manifest.read_config()
672 self.assertEqual(ignore, check_manifest.IgnoreList.default())
673
674 def test_read_setup_config_no_option(self):
675 import check_manifest
676 with open('setup.cfg', 'w') as f:
677 f.write('[check-manifest]\n')
678 ignore, ignore_bad_ideas = check_manifest.read_config()
679 self.assertEqual(ignore, check_manifest.IgnoreList.default())
680
681 def test_read_pyproject_config_no_option(self):
682 import check_manifest
683 with open('pyproject.toml', 'w') as f:
684 f.write('[tool.check-manifest]\n')
685 ignore, ignore_bad_ideas = check_manifest.read_config()
686 self.assertEqual(ignore, check_manifest.IgnoreList.default())
687
688 def test_read_setup_config_extra_ignores(self):
689 import check_manifest
690 with open('setup.cfg', 'w') as f:
691 f.write('[check-manifest]\nignore = foo\n bar*\n')
692 ignore, ignore_bad_ideas = check_manifest.read_config()
693 expected = check_manifest.IgnoreList.default().global_exclude('foo', 'bar*')
694 self.assertEqual(ignore, expected)
695
696 def test_read_pyproject_config_extra_ignores(self):
697 import check_manifest
698 with open('pyproject.toml', 'w') as f:
699 f.write('[tool.check-manifest]\nignore = ["foo", "bar*"]\n')
700 ignore, ignore_bad_ideas = check_manifest.read_config()
701 expected = check_manifest.IgnoreList.default().global_exclude('foo', 'bar*')
702 self.assertEqual(ignore, expected)
703
704 def test_read_setup_config_override_ignores(self):
705 import check_manifest
706 with open('setup.cfg', 'w') as f:
707 f.write('[check-manifest]\nignore = foo\n\n bar\n')
708 f.write('ignore-default-rules = yes\n')
709 ignore, ignore_bad_ideas = check_manifest.read_config()
710 expected = check_manifest.IgnoreList().global_exclude('foo', 'bar')
711 self.assertEqual(ignore, expected)
712
713 def test_read_pyproject_config_override_ignores(self):
714 import check_manifest
715 with open('pyproject.toml', 'w') as f:
716 f.write('[tool.check-manifest]\nignore = ["foo", "bar"]\n')
717 f.write('ignore-default-rules = true\n')
718 ignore, ignore_bad_ideas = check_manifest.read_config()
719 expected = check_manifest.IgnoreList().global_exclude('foo', 'bar')
720 self.assertEqual(ignore, expected)
721
722 def test_read_setup_config_ignore_bad_ideas(self):
723 import check_manifest
724 with open('setup.cfg', 'w') as f:
725 f.write('[check-manifest]\n'
726 'ignore-bad-ideas = \n'
727 ' foo\n'
728 ' bar*\n')
729 ignore, ignore_bad_ideas = check_manifest.read_config()
730 expected = check_manifest.IgnoreList().global_exclude('foo', 'bar*')
731 self.assertEqual(ignore_bad_ideas, expected)
732
733 def test_read_pyproject_config_ignore_bad_ideas(self):
734 import check_manifest
735 with open('pyproject.toml', 'w') as f:
736 f.write('[tool.check-manifest]\n'
737 'ignore-bad-ideas = ["foo", "bar*"]\n')
738 ignore, ignore_bad_ideas = check_manifest.read_config()
739 expected = check_manifest.IgnoreList().global_exclude('foo', 'bar*')
740 self.assertEqual(ignore_bad_ideas, expected)
741
742 def test_read_manifest_no_manifest(self):
743 import check_manifest
744 ignore = check_manifest.read_manifest(self.ui)
745 self.assertEqual(ignore, check_manifest.IgnoreList())
746
747 def test_read_manifest(self):
748 import check_manifest
749 from check_manifest import IgnoreList
750 with open('MANIFEST.in', 'w') as f:
751 f.write('exclude *.gif\n')
752 f.write('global-exclude *.png\n')
753 ignore = check_manifest.read_manifest(self.ui)
754 self.assertEqual(ignore, IgnoreList().exclude('*.gif').global_exclude('*.png'))
755
756
757 class TestMain(unittest.TestCase):
758
759 def setUp(self):
760 self._cm_patcher = mock.patch('check_manifest.check_manifest')
761 self._check_manifest = self._cm_patcher.start()
762 self._se_patcher = mock.patch('sys.exit')
763 self._sys_exit = self._se_patcher.start()
764 self.ui = MockUI()
765 self._ui_patcher = mock.patch('check_manifest.UI', self._make_ui)
766 self._ui_patcher.start()
767 self._orig_sys_argv = sys.argv
768 sys.argv = ['check-manifest']
769
770 def tearDown(self):
771 sys.argv = self._orig_sys_argv
772 self._se_patcher.stop()
773 self._cm_patcher.stop()
774 self._ui_patcher.stop()
775
776 def _make_ui(self, verbosity):
777 self.ui.verbosity = verbosity
778 return self.ui
779
780 def test(self):
781 from check_manifest import main
782 sys.argv.append('-v')
783 main()
784
785 def test_exit_code_1_on_error(self):
786 from check_manifest import main
787 self._check_manifest.return_value = False
788 main()
789 self._sys_exit.assert_called_with(1)
790
791 def test_exit_code_2_on_failure(self):
792 from check_manifest import Failure, main
793 self._check_manifest.side_effect = Failure('msg')
794 main()
795 self.assertEqual(self.ui.errors, ['msg'])
796 self._sys_exit.assert_called_with(2)
797
798 def test_extra_ignore_args(self):
799 import check_manifest
800 sys.argv.append('--ignore=x,y,z*')
801 check_manifest.main()
802 ignore = check_manifest.IgnoreList().global_exclude('x', 'y', 'z*')
803 self.assertEqual(self._check_manifest.call_args.kwargs['extra_ignore'],
804 ignore)
805
806 def test_ignore_bad_ideas_args(self):
807 import check_manifest
808 sys.argv.append('--ignore-bad-ideas=x,y,z*')
809 check_manifest.main()
810 ignore = check_manifest.IgnoreList().global_exclude('x', 'y', 'z*')
811 self.assertEqual(self._check_manifest.call_args.kwargs['extra_ignore_bad_ideas'],
812 ignore)
813
814 def test_verbose_arg(self):
815 import check_manifest
816 sys.argv.append('--verbose')
817 check_manifest.main()
818 self.assertEqual(self.ui.verbosity, 2)
819
820 def test_quiet_arg(self):
821 import check_manifest
822 sys.argv.append('--quiet')
823 check_manifest.main()
824 self.assertEqual(self.ui.verbosity, 0)
825
826 def test_verbose_and_quiet_arg(self):
827 import check_manifest
828 sys.argv.append('--verbose')
829 sys.argv.append('--quiet')
830 check_manifest.main()
831 # the two arguments cancel each other out:
832 # 1 (default verbosity) + 1 - 1 = 1.
833 self.assertEqual(self.ui.verbosity, 1)
834
835
836 class TestZestIntegration(unittest.TestCase):
837
838 def setUp(self):
839 sys.modules['zest'] = mock.Mock()
840 sys.modules['zest.releaser'] = mock.Mock()
841 sys.modules['zest.releaser.utils'] = mock.Mock()
842 self.ask = sys.modules['zest.releaser.utils'].ask
843 self.ui = MockUI()
844 self._ui_patcher = mock.patch('check_manifest.UI', return_value=self.ui)
845 self._ui_patcher.start()
846
847 def tearDown(self):
848 self._ui_patcher.stop()
849 del sys.modules['zest.releaser.utils']
850 del sys.modules['zest.releaser']
851 del sys.modules['zest']
852
853 @mock.patch('check_manifest.is_package', lambda d: False)
854 @mock.patch('check_manifest.check_manifest')
855 def test_zest_releaser_check_not_a_package(self, check_manifest):
856 from check_manifest import zest_releaser_check
857 zest_releaser_check(dict(workingdir='.'))
858 check_manifest.assert_not_called()
859
860 @mock.patch('check_manifest.is_package', lambda d: True)
861 @mock.patch('check_manifest.check_manifest')
862 def test_zest_releaser_check_user_disagrees(self, check_manifest):
863 from check_manifest import zest_releaser_check
864 self.ask.return_value = False
865 zest_releaser_check(dict(workingdir='.'))
866 check_manifest.assert_not_called()
867
868 @mock.patch('check_manifest.is_package', lambda d: True)
869 @mock.patch('sys.exit')
870 @mock.patch('check_manifest.check_manifest')
871 def test_zest_releaser_check_all_okay(self, check_manifest, sys_exit):
872 from check_manifest import zest_releaser_check
873 self.ask.return_value = True
874 check_manifest.return_value = True
875 zest_releaser_check(dict(workingdir='.'))
876 sys_exit.assert_not_called()
877
878 @mock.patch('check_manifest.is_package', lambda d: True)
879 @mock.patch('sys.exit')
880 @mock.patch('check_manifest.check_manifest')
881 def test_zest_releaser_check_error_user_aborts(self, check_manifest,
882 sys_exit):
883 from check_manifest import zest_releaser_check
884 self.ask.side_effect = [True, False]
885 check_manifest.return_value = False
886 zest_releaser_check(dict(workingdir='.'))
887 sys_exit.assert_called_with(1)
888
889 @mock.patch('check_manifest.is_package', lambda d: True)
890 @mock.patch('sys.exit')
891 @mock.patch('check_manifest.check_manifest')
892 def test_zest_releaser_check_error_user_plods_on(self, check_manifest,
893 sys_exit):
894 from check_manifest import zest_releaser_check
895 self.ask.side_effect = [True, True]
896 check_manifest.return_value = False
897 zest_releaser_check(dict(workingdir='.'))
898 sys_exit.assert_not_called()
899
900 @mock.patch('check_manifest.is_package', lambda d: True)
901 @mock.patch('sys.exit')
902 @mock.patch('check_manifest.check_manifest')
903 def test_zest_releaser_check_failure_user_aborts(self, check_manifest,
904 sys_exit):
905 from check_manifest import Failure, zest_releaser_check
906 self.ask.side_effect = [True, False]
907 check_manifest.side_effect = Failure('msg')
908 zest_releaser_check(dict(workingdir='.'))
909 self.assertEqual(self.ui.errors, ['msg'])
910 sys_exit.assert_called_with(2)
911
912 @mock.patch('check_manifest.is_package', lambda d: True)
913 @mock.patch('sys.exit')
914 @mock.patch('check_manifest.check_manifest')
915 def test_zest_releaser_check_failure_user_plods_on(self, check_manifest,
916 sys_exit):
917 from check_manifest import Failure, zest_releaser_check
918 self.ask.side_effect = [True, True]
919 check_manifest.side_effect = Failure('msg')
920 zest_releaser_check(dict(workingdir='.'))
921 self.assertEqual(self.ui.errors, ['msg'])
922 sys_exit.assert_not_called()
923
924
925 class VCSHelper:
926
927 # override in subclasses
928 command: Optional[str] = None
929 extra_env: Dict[str, str] = {}
930
931 @property
932 def version(self):
933 if not hasattr(self, '_version'):
934 if not self.is_installed():
935 self._version = None
936 return self._version
937
938 @property
939 def version_tuple(self):
940 return tuple(map(int, re.findall(r'\d+', self.version)))
941
942 def is_installed(self):
943 try:
944 p = subprocess.Popen([self.command, '--version'],
945 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
946 stdout, stderr = p.communicate()
947 self._version = stdout.decode('ascii', 'backslashreplace').strip()
948 rc = p.wait()
949 return (rc == 0)
950 except OSError:
951 return False
952
953 def _run(self, *command):
954 # Windows doesn't like Unicode arguments to subprocess.Popen(), on Py2:
955 # https://github.com/mgedmin/check-manifest/issues/23#issuecomment-33933031
956 if str is bytes:
957 command = [s.encode(locale.getpreferredencoding()) for s in command]
958 print('$', ' '.join(command))
959 p = subprocess.Popen(command, stdout=subprocess.PIPE,
960 stderr=subprocess.STDOUT,
961 env={**os.environ, **self.extra_env})
962 stdout, stderr = p.communicate()
963 rc = p.wait()
964 if stdout:
965 print(stdout.decode('ascii', 'backslashreplace'))
966 if rc:
967 raise subprocess.CalledProcessError(rc, command[0], output=stdout)
968
969
970 class VCSMixin:
971
972 def setUp(self):
973 if not self.vcs.is_installed() and CAN_SKIP_TESTS:
974 self.skipTest("%s is not installed" % self.vcs.command)
975 self.tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
976 self.olddir = os.getcwd()
977 os.chdir(self.tmpdir)
978 self.ui = MockUI()
979
980 def tearDown(self):
981 os.chdir(self.olddir)
982 rmtree(self.tmpdir)
983
984 def _create_file(self, filename):
985 assert not os.path.isabs(filename)
986 basedir = os.path.dirname(filename)
987 if basedir and not os.path.isdir(basedir):
988 os.makedirs(basedir)
989 open(filename, 'w').close()
990
991 def _create_files(self, filenames):
992 for filename in filenames:
993 self._create_file(filename)
994
995 def _init_vcs(self):
996 self.vcs._init_vcs()
997
998 def _add_to_vcs(self, filenames):
999 self.vcs._add_to_vcs(filenames)
1000
1001 def _commit(self):
1002 self.vcs._commit()
1003
1004 def _create_and_add_to_vcs(self, filenames):
1005 self._create_files(filenames)
1006 self._add_to_vcs(filenames)
1007
1008 def test_get_vcs_files(self):
1009 from check_manifest import get_vcs_files
1010 self._init_vcs()
1011 self._create_and_add_to_vcs(['a.txt', 'b/b.txt', 'b/c/d.txt'])
1012 self._commit()
1013 self._create_files(['b/x.txt', 'd/d.txt', 'i.txt'])
1014 self.assertEqual(get_vcs_files(self.ui),
1015 ['a.txt', 'b/b.txt', 'b/c/d.txt'])
1016
1017 def test_get_vcs_files_added_but_uncommitted(self):
1018 from check_manifest import get_vcs_files
1019 self._init_vcs()
1020 self._create_and_add_to_vcs(['a.txt', 'b/b.txt', 'b/c/d.txt'])
1021 self._create_files(['b/x.txt', 'd/d.txt', 'i.txt'])
1022 self.assertEqual(get_vcs_files(self.ui),
1023 ['a.txt', 'b/b.txt', 'b/c/d.txt'])
1024
1025 def test_get_vcs_files_deleted_but_not_removed(self):
1026 if self.vcs.command == 'bzr':
1027 self.skipTest("this cosmetic feature is not supported with bzr")
1028 # see the longer explanation in test_missing_source_files
1029 from check_manifest import get_vcs_files
1030 self._init_vcs()
1031 self._create_and_add_to_vcs(['a.txt'])
1032 self._commit()
1033 os.unlink('a.txt')
1034 self.assertEqual(get_vcs_files(self.ui), ['a.txt'])
1035
1036 def test_get_vcs_files_in_a_subdir(self):
1037 from check_manifest import get_vcs_files
1038 self._init_vcs()
1039 self._create_and_add_to_vcs(['a.txt', 'b/b.txt', 'b/c/d.txt'])
1040 self._commit()
1041 self._create_files(['b/x.txt', 'd/d.txt', 'i.txt'])
1042 os.chdir('b')
1043 self.assertEqual(get_vcs_files(self.ui), ['b.txt', 'c/d.txt'])
1044
1045 @unittest.skipIf(
1046 sys.platform == 'win32',
1047 "Get yourself a real VCS running on a real OS, I can't support this mess",
1048 )
1049 def test_get_vcs_files_nonascii_filenames(self):
1050 # This test will fail if your locale is incapable of expressing
1051 # "eacute". UTF-8 or Latin-1 should work.
1052 from check_manifest import Bazaar
1053 print("Detected terminal encoding: ", Bazaar._get_terminal_encoding())
1054 print("sys.stdin.isatty():", sys.stdin.isatty())
1055 print("sys.stdout.isatty():", sys.stdout.isatty())
1056 print("sys.stdin.encoding:", getattr(sys.stdin, 'encoding', 'missing'))
1057 print("sys.stdout.encoding:", getattr(sys.stdout, 'encoding', 'missing'))
1058 from check_manifest import get_vcs_files
1059 self._init_vcs()
1060 filename = "\u00E9.txt"
1061 self._create_and_add_to_vcs([filename])
1062 self.assertEqual(get_vcs_files(self.ui), [filename])
1063
1064 def test_get_vcs_files_empty(self):
1065 from check_manifest import get_vcs_files
1066 self._init_vcs()
1067 self.assertEqual(get_vcs_files(self.ui), [])
1068
1069
1070 class GitHelper(VCSHelper):
1071
1072 command = 'git'
1073 extra_env = dict(
1074 GIT_ALLOW_PROTOCOL='file',
1075 )
1076
1077 def _init_vcs(self):
1078 if self.version_tuple >= (2, 28):
1079 self._run('git', 'init', '-b', 'main')
1080 else:
1081 self._run('git', 'init')
1082 self._run('git', 'config', 'user.name', 'Unit Test')
1083 self._run('git', 'config', 'user.email', '[email protected]')
1084
1085 def _add_to_vcs(self, filenames):
1086 # Note that we use --force to prevent errors when we want to
1087 # add foo.egg-info and the user running the tests has
1088 # '*.egg-info' in her global .gitignore file.
1089 self._run('git', 'add', '--force', '--', *filenames)
1090
1091 def _commit(self):
1092 self._run('git', 'commit', '-m', 'Initial')
1093
1094
1095 class TestGit(VCSMixin, unittest.TestCase):
1096 vcs = GitHelper()
1097
1098 def _init_repo_with_files(self, dirname, filenames):
1099 os.mkdir(dirname)
1100 os.chdir(dirname)
1101 self._init_vcs()
1102 self._create_and_add_to_vcs(filenames)
1103 self._commit()
1104 os.chdir(self.tmpdir)
1105
1106 def _add_submodule(self, repo, subdir, subrepo):
1107 os.chdir(repo)
1108 self.vcs._run('git', 'submodule', 'add', subrepo, subdir)
1109 self._commit()
1110 os.chdir(self.tmpdir)
1111
1112 def test_detect_git_submodule(self):
1113 from check_manifest import Failure, detect_vcs
1114 with self.assertRaises(Failure) as cm:
1115 detect_vcs(self.ui)
1116 self.assertEqual(str(cm.exception),
1117 "Couldn't find version control data"
1118 " (git/hg/bzr/svn supported)")
1119 # now create a .git file like in a submodule
1120 open(os.path.join(self.tmpdir, '.git'), 'w').close()
1121 self.assertEqual(detect_vcs(self.ui).metadata_name, '.git')
1122
1123 def test_get_versioned_files_with_git_submodules(self):
1124 from check_manifest import get_vcs_files
1125 self._init_repo_with_files('repo1', ['file1', 'file2'])
1126 self._init_repo_with_files('repo2', ['file3'])
1127 self._init_repo_with_files('repo3', ['file4'])
1128 self._add_submodule('repo2', 'sub3', '../repo3')
1129 self._init_repo_with_files('main', ['file5', 'subdir/file6'])
1130 self._add_submodule('main', 'sub1', '../repo1')
1131 self._add_submodule('main', 'subdir/sub2', '../repo2')
1132 os.chdir('main')
1133 self.vcs._run('git', 'submodule', 'update', '--init', '--recursive')
1134 self.assertEqual(
1135 get_vcs_files(self.ui),
1136 [
1137 '.gitmodules',
1138 'file5',
1139 'sub1/file1',
1140 'sub1/file2',
1141 'subdir/file6',
1142 'subdir/sub2/.gitmodules',
1143 'subdir/sub2/file3',
1144 'subdir/sub2/sub3/file4',
1145 ])
1146
1147 def test_get_versioned_files_with_git_submodules_with_git_index_file_set(self):
1148 with mock.patch.dict(os.environ, {"GIT_INDEX_FILE": ".git/index"}):
1149 self.test_get_versioned_files_with_git_submodules()
1150
1151
1152 class BzrHelper(VCSHelper):
1153
1154 command = 'bzr'
1155
1156 def _init_vcs(self):
1157 # See Debian bug #941558.
1158 bzrconfig = os.path.expanduser ("~/.config/breezy/")
1159 if not os.path.exists (bzrconfig):
1160 os.makedirs (bzrconfig)
1161
1162 self._run('bzr', 'init')
1163 self._run('bzr', 'whoami', '--branch', 'Unit Test <[email protected]>')
1164
1165 def _add_to_vcs(self, filenames):
1166 self._run('bzr', 'add', '--', *filenames)
1167
1168 def _commit(self):
1169 self._run('bzr', 'commit', '-m', 'Initial')
1170
1171
1172 class TestBzr(VCSMixin, unittest.TestCase):
1173 vcs = BzrHelper()
1174
1175
1176 @unittest.skipIf(HAS_OEM_CODEC,
1177 "Python 3.6 lets us use 'oem' codec instead of guessing")
1178 class TestBzrTerminalCharsetDetectionOnOldPythons(unittest.TestCase):
1179
1180 @mock.patch('sys.stdin')
1181 @mock.patch('sys.stdout')
1182 def test_terminal_encoding_not_known(self, mock_stdout, mock_stdin):
1183 from check_manifest import Bazaar
1184 mock_stdout.encoding = None
1185 mock_stdin.encoding = None
1186 self.assertEqual(Bazaar._get_terminal_encoding(), None)
1187
1188 @mock.patch('sys.stdout')
1189 def test_terminal_encoding_stdout_known(self, mock_stdout):
1190 from check_manifest import Bazaar
1191 mock_stdout.encoding = 'UTF-8'
1192 self.assertEqual(Bazaar._get_terminal_encoding(), 'UTF-8')
1193
1194 @mock.patch('sys.stdin')
1195 @mock.patch('sys.stdout')
1196 def test_terminal_encoding_stdin_known(self, mock_stdout, mock_stdin):
1197 from check_manifest import Bazaar
1198 mock_stdout.encoding = None
1199 mock_stdin.encoding = 'UTF-8'
1200 self.assertEqual(Bazaar._get_terminal_encoding(), 'UTF-8')
1201
1202 @mock.patch('sys.stdout')
1203 def test_terminal_encoding_cp0(self, mock_stdout):
1204 from check_manifest import Bazaar
1205 mock_stdout.encoding = 'cp0'
1206 self.assertEqual(Bazaar._get_terminal_encoding(), None)
1207
1208
1209 @unittest.skipIf(not HAS_OEM_CODEC,
1210 "'oem' codec not available on Python before 3.6")
1211 class TestBzrTerminalCharsetDetectionOnNewPythons(unittest.TestCase):
1212
1213 def test_terminal_encoding_cp0(self):
1214 from check_manifest import Bazaar
1215 self.assertEqual(Bazaar._get_terminal_encoding(), "oem")
1216
1217
1218 class HgHelper(VCSHelper):
1219
1220 command = 'hg'
1221
1222 def _init_vcs(self):
1223 self._run('hg', 'init')
1224 with open('.hg/hgrc', 'a') as f:
1225 f.write('\n[ui]\nusername = Unit Test <[email protected]\n')
1226
1227 def _add_to_vcs(self, filenames):
1228 self._run('hg', 'add', '--', *filenames)
1229
1230 def _commit(self):
1231 self._run('hg', 'commit', '-m', 'Initial')
1232
1233
1234 class TestHg(VCSMixin, unittest.TestCase):
1235 vcs = HgHelper()
1236
1237
1238 class SvnHelper(VCSHelper):
1239
1240 command = 'svn'
1241
1242 def _init_vcs(self):
1243 self._run('svnadmin', 'create', 'repo')
1244 self._run('svn', 'co', 'file:///' + os.path.abspath('repo').replace(os.path.sep, '/'), 'checkout')
1245 os.chdir('checkout')
1246
1247 def _add_directories_and_sort(self, filelist):
1248 from check_manifest import normalize_names
1249 names = set(normalize_names(filelist))
1250 names.update([posixpath.dirname(fn) for fn in names])
1251 return sorted(names - {''})
1252
1253 def _add_to_vcs(self, filenames):
1254 self._run('svn', 'add', '-N', '--', *self._add_directories_and_sort(filenames))
1255
1256 def _commit(self):
1257 self._run('svn', 'commit', '-m', 'Initial')
1258
1259
1260 class TestSvn(VCSMixin, unittest.TestCase):
1261 vcs = SvnHelper()
1262
1263 def test_svn_externals(self):
1264 from check_manifest import get_vcs_files
1265 self.vcs._run('svnadmin', 'create', 'repo2')
1266 repo2_url = 'file:///' + os.path.abspath('repo2').replace(os.path.sep, '/')
1267 self.vcs._init_vcs()
1268 self.vcs._run('svn', 'propset', 'svn:externals', 'ext %s' % repo2_url, '.')
1269 self.vcs._run('svn', 'up')
1270 self._create_files(['a.txt', 'ext/b.txt'])
1271 self.vcs._run('svn', 'add', 'a.txt', 'ext/b.txt')
1272 self.assertEqual(get_vcs_files(self.ui),
1273 ['a.txt', 'ext/b.txt'])
1274
1275
1276 class TestSvnExtraErrors(unittest.TestCase):
1277
1278 def test_svn_xml_parsing_warning(self):
1279 from check_manifest import Subversion
1280 ui = MockUI()
1281 svn = Subversion(ui)
1282 entry = ET.XML('<entry path="foo/bar.txt"></entry>')
1283 self.assertFalse(svn.is_interesting(entry))
1284 self.assertEqual(
1285 ui.warnings,
1286 ['svn status --xml parse error:'
1287 ' <entry path="foo/bar.txt"> without <wc-status>'])
1288
1289
1290 class TestUserInterface(unittest.TestCase):
1291
1292 def make_ui(self, verbosity=1):
1293 from check_manifest import UI
1294 ui = UI(verbosity=verbosity)
1295 ui.stdout = StringIO()
1296 ui.stderr = StringIO()
1297 return ui
1298
1299 def test_info(self):
1300 ui = self.make_ui(verbosity=1)
1301 ui.info("Reticulating splines")
1302 self.assertEqual(ui.stdout.getvalue(),
1303 "Reticulating splines\n")
1304
1305 def test_info_verbose(self):
1306 ui = self.make_ui(verbosity=2)
1307 ui.info("Reticulating splines")
1308 self.assertEqual(ui.stdout.getvalue(),
1309 "Reticulating splines\n")
1310
1311 def test_info_quiet(self):
1312 ui = self.make_ui(verbosity=0)
1313 ui.info("Reticulating splines")
1314 self.assertEqual(ui.stdout.getvalue(), "")
1315
1316 def test_info_begin_continue_end(self):
1317 ui = self.make_ui(verbosity=1)
1318 ui.info_begin("Reticulating splines...")
1319 ui.info_continue(" nearly done...")
1320 ui.info_continue(" almost done...")
1321 ui.info_end(" done!")
1322 self.assertEqual(ui.stdout.getvalue(), "")
1323
1324 def test_info_begin_continue_end_verbose(self):
1325 ui = self.make_ui(verbosity=2)
1326 ui.info_begin("Reticulating splines...")
1327 ui.info_continue(" nearly done...")
1328 ui.info_continue(" almost done...")
1329 ui.info_end(" done!")
1330 self.assertEqual(
1331 ui.stdout.getvalue(),
1332 "Reticulating splines... nearly done... almost done... done!\n")
1333
1334 def test_info_emits_newline_when_needed(self):
1335 ui = self.make_ui(verbosity=1)
1336 ui.info_begin("Computering...")
1337 ui.info("Forgot to turn the gas off!")
1338 self.assertEqual(
1339 ui.stdout.getvalue(),
1340 "Forgot to turn the gas off!\n")
1341
1342 def test_info_emits_newline_when_needed_verbose(self):
1343 ui = self.make_ui(verbosity=2)
1344 ui.info_begin("Computering...")
1345 ui.info("Forgot to turn the gas off!")
1346 self.assertEqual(
1347 ui.stdout.getvalue(),
1348 "Computering...\n"
1349 "Forgot to turn the gas off!\n")
1350
1351 def test_warning(self):
1352 ui = self.make_ui(verbosity=1)
1353 ui.info_begin("Computering...")
1354 ui.warning("Forgot to turn the gas off!")
1355 self.assertEqual(ui.stdout.getvalue(), "")
1356 self.assertEqual(
1357 ui.stderr.getvalue(),
1358 "Forgot to turn the gas off!\n")
1359
1360 def test_warning_verbose(self):
1361 ui = self.make_ui(verbosity=2)
1362 ui.info_begin("Computering...")
1363 ui.warning("Forgot to turn the gas off!")
1364 self.assertEqual(
1365 ui.stdout.getvalue(),
1366 "Computering...\n")
1367 self.assertEqual(
1368 ui.stderr.getvalue(),
1369 "Forgot to turn the gas off!\n")
1370
1371 def test_error(self):
1372 ui = self.make_ui(verbosity=1)
1373 ui.info_begin("Computering...")
1374 ui.error("Forgot to turn the gas off!")
1375 self.assertEqual(ui.stdout.getvalue(), "")
1376 self.assertEqual(
1377 ui.stderr.getvalue(),
1378 "Forgot to turn the gas off!\n")
1379
1380 def test_error_verbose(self):
1381 ui = self.make_ui(verbosity=2)
1382 ui.info_begin("Computering...")
1383 ui.error("Forgot to turn the gas off!")
1384 self.assertEqual(
1385 ui.stdout.getvalue(),
1386 "Computering...\n")
1387 self.assertEqual(
1388 ui.stderr.getvalue(),
1389 "Forgot to turn the gas off!\n")
1390
1391
1392 class TestIgnoreList(unittest.TestCase):
1393
1394 def setUp(self):
1395 from check_manifest import IgnoreList
1396 self.ignore = IgnoreList()
1397
1398 def test_repr(self):
1399 from check_manifest import IgnoreList
1400 ignore = IgnoreList()
1401 self.assertEqual(repr(ignore), "IgnoreList([])")
1402
1403 def test_exclude_pattern(self):
1404 self.ignore.exclude('*.txt')
1405 self.assertEqual(self.ignore.filter([
1406 'foo.md',
1407 'bar.txt',
1408 'subdir/bar.txt',
1409 ]), [
1410 'foo.md',
1411 'subdir/bar.txt',
1412 ])
1413
1414 def test_exclude_file(self):
1415 self.ignore.exclude('bar.txt')
1416 self.assertEqual(self.ignore.filter([
1417 'foo.md',
1418 'bar.txt',
1419 'subdir/bar.txt',
1420 ]), [
1421 'foo.md',
1422 'subdir/bar.txt',
1423 ])
1424
1425 def test_exclude_doest_apply_to_directories(self):
1426 self.ignore.exclude('subdir')
1427 self.assertEqual(self.ignore.filter([
1428 'foo.md',
1429 'subdir/bar.txt',
1430 ]), [
1431 'foo.md',
1432 'subdir/bar.txt',
1433 ])
1434
1435 def test_global_exclude(self):
1436 self.ignore.global_exclude('a*.txt')
1437 self.assertEqual(self.ignore.filter([
1438 'bar.txt', # make sure full filenames are matched
1439 'afile.txt',
1440 'subdir/afile.txt',
1441 'adir/file.txt', # make sure * doesn't match /
1442 ]), [
1443 'bar.txt',
1444 'adir/file.txt',
1445 ])
1446
1447 def test_global_exclude_does_not_apply_to_directories(self):
1448 self.ignore.global_exclude('subdir')
1449 self.assertEqual(self.ignore.filter([
1450 'bar.txt',
1451 'subdir/afile.txt',
1452 ]), [
1453 'bar.txt',
1454 'subdir/afile.txt',
1455 ])
1456
1457 def test_recursive_exclude(self):
1458 self.ignore.recursive_exclude('subdir', 'a*.txt')
1459 self.assertEqual(self.ignore.filter([
1460 'afile.txt',
1461 'subdir/afile.txt',
1462 'subdir/extra/afile.txt',
1463 'subdir/adir/file.txt',
1464 'other/afile.txt',
1465 ]), [
1466 'afile.txt',
1467 'subdir/adir/file.txt',
1468 'other/afile.txt',
1469 ])
1470
1471 def test_recursive_exclude_does_not_apply_to_directories(self):
1472 self.ignore.recursive_exclude('subdir', 'dir')
1473 self.assertEqual(self.ignore.filter([
1474 'afile.txt',
1475 'subdir/dir/afile.txt',
1476 ]), [
1477 'afile.txt',
1478 'subdir/dir/afile.txt',
1479 ])
1480
1481 def test_recursive_exclude_can_prune(self):
1482 self.ignore.recursive_exclude('subdir', '*')
1483 self.assertEqual(self.ignore.filter([
1484 'afile.txt',
1485 'subdir/afile.txt',
1486 'subdir/dir/afile.txt',
1487 'subdir/dir/dir/afile.txt',
1488 ]), [
1489 'afile.txt',
1490 ])
1491
1492 def test_prune(self):
1493 self.ignore.prune('subdir')
1494 self.assertEqual(self.ignore.filter([
1495 'foo.md',
1496 'subdir/bar.txt',
1497 'unrelated/subdir/baz.txt',
1498 ]), [
1499 'foo.md',
1500 'unrelated/subdir/baz.txt',
1501 ])
1502
1503 def test_prune_subdir(self):
1504 self.ignore.prune('a/b')
1505 self.assertEqual(self.ignore.filter([
1506 'foo.md',
1507 'a/b/bar.txt',
1508 'a/c/bar.txt',
1509 ]), [
1510 'foo.md',
1511 'a/c/bar.txt',
1512 ])
1513
1514 def test_prune_glob(self):
1515 self.ignore.prune('su*r')
1516 self.assertEqual(self.ignore.filter([
1517 'foo.md',
1518 'subdir/bar.txt',
1519 'unrelated/subdir/baz.txt',
1520 ]), [
1521 'foo.md',
1522 'unrelated/subdir/baz.txt',
1523 ])
1524
1525 def test_prune_glob_is_not_too_greedy(self):
1526 self.ignore.prune('su*r')
1527 self.assertEqual(self.ignore.filter([
1528 'foo.md',
1529 # super-unrelated/subdir matches su*r if you allow * to match /,
1530 # which fnmatch does!
1531 'super-unrelated/subdir/qux.txt',
1532 ]), [
1533 'foo.md',
1534 'super-unrelated/subdir/qux.txt',
1535 ])
1536
1537 def test_default_excludes_pkg_info(self):
1538 from check_manifest import IgnoreList
1539 ignore = IgnoreList.default()
1540 self.assertEqual(ignore.filter([
1541 'PKG-INFO',
1542 'bar.txt',
1543 ]), [
1544 'bar.txt',
1545 ])
1546
1547 def test_default_excludes_egg_info(self):
1548 from check_manifest import IgnoreList
1549 ignore = IgnoreList.default()
1550 self.assertEqual(ignore.filter([
1551 'mypackage.egg-info/PKG-INFO',
1552 'mypackage.egg-info/SOURCES.txt',
1553 'mypackage.egg-info/requires.txt',
1554 'bar.txt',
1555 ]), [
1556 'bar.txt',
1557 ])
1558
1559 def test_default_excludes_egg_info_in_a_subdirectory(self):
1560 from check_manifest import IgnoreList
1561 ignore = IgnoreList.default()
1562 self.assertEqual(ignore.filter([
1563 'src/mypackage.egg-info/PKG-INFO',
1564 'src/mypackage.egg-info/SOURCES.txt',
1565 'src/mypackage.egg-info/requires.txt',
1566 'bar.txt',
1567 ]), [
1568 'bar.txt',
1569 ])
1570
1571
1572 def pick_installed_vcs():
1573 preferred_order = [GitHelper, HgHelper, BzrHelper, SvnHelper]
1574 force = os.getenv('FORCE_TEST_VCS')
1575 if force:
1576 for cls in preferred_order:
1577 if force == cls.command:
1578 return cls()
1579 raise ValueError('Unsupported FORCE_TEST_VCS=%s (supported: %s)'
1580 % (force, '/'.join(cls.command for cls in preferred_order)))
1581 for cls in preferred_order:
1582 vcs = cls()
1583 if vcs.is_installed():
1584 return vcs
1585 return None
1586
1587
1588 class TestCheckManifest(unittest.TestCase):
1589
1590 _vcs = pick_installed_vcs()
1591
1592 def setUp(self):
1593 if self._vcs is None:
1594 self.fail('at least one version control system should be installed')
1595 self.oldpwd = os.getcwd()
1596 self.tmpdir = tempfile.mkdtemp(prefix='test-', suffix='-check-manifest')
1597 os.chdir(self.tmpdir)
1598 self._stdout_patcher = mock.patch('sys.stdout', StringIO())
1599 self._stdout_patcher.start()
1600 self._stderr_patcher = mock.patch('sys.stderr', StringIO())
1601 self._stderr_patcher.start()
1602
1603 def tearDown(self):
1604 self._stderr_patcher.stop()
1605 self._stdout_patcher.stop()
1606 os.chdir(self.oldpwd)
1607 rmtree(self.tmpdir)
1608
1609 def _create_repo_with_code(self, add_to_vcs=True):
1610 self._vcs._init_vcs()
1611 with open('setup.py', 'w') as f:
1612 f.write("from setuptools import setup\n")
1613 f.write("setup(name='sample', py_modules=['sample'])\n")
1614 with open('sample.py', 'w') as f:
1615 f.write("# wow. such code. so amaze\n")
1616 if add_to_vcs:
1617 self._vcs._add_to_vcs(['setup.py', 'sample.py'])
1618
1619 def _create_repo_with_code_in_subdir(self):
1620 os.mkdir('subdir')
1621 os.chdir('subdir')
1622 self._create_repo_with_code()
1623 # NB: when self._vcs is SvnHelper, we're actually in
1624 # ./subdir/checkout rather than in ./subdir
1625 subdir = os.path.basename(os.getcwd())
1626 os.chdir(os.pardir)
1627 return subdir
1628
1629 def _add_to_vcs(self, filename, content=''):
1630 if os.path.sep in filename and not os.path.isdir(os.path.dirname(filename)):
1631 os.makedirs(os.path.dirname(filename))
1632 with open(filename, 'w') as f:
1633 f.write(content)
1634 self._vcs._add_to_vcs([filename])
1635
1636 def test_not_python_project(self):
1637 from check_manifest import Failure, check_manifest
1638 with self.assertRaises(Failure) as cm:
1639 check_manifest()
1640 self.assertEqual(
1641 str(cm.exception),
1642 "This is not a Python project (no setup.py/pyproject.toml).")
1643
1644 def test_forgot_to_git_add_anything(self):
1645 from check_manifest import Failure, check_manifest
1646 self._create_repo_with_code(add_to_vcs=False)
1647 with self.assertRaises(Failure) as cm:
1648 check_manifest()
1649 self.assertEqual(str(cm.exception),
1650 "There are no files added to version control!")
1651
1652 def test_all_is_well(self):
1653 from check_manifest import check_manifest
1654 self._create_repo_with_code()
1655 self.assertTrue(check_manifest(), sys.stderr.getvalue())
1656
1657 def test_relative_pathname(self):
1658 from check_manifest import check_manifest
1659 subdir = self._create_repo_with_code_in_subdir()
1660 self.assertTrue(check_manifest(subdir), sys.stderr.getvalue())
1661
1662 def test_relative_python(self):
1663 # https://github.com/mgedmin/check-manifest/issues/36
1664 from check_manifest import check_manifest
1665 subdir = self._create_repo_with_code_in_subdir()
1666 python = os.path.relpath(sys.executable)
1667 self.assertTrue(check_manifest(subdir, python=python),
1668 sys.stderr.getvalue())
1669
1670 def test_python_from_path(self):
1671 # https://github.com/mgedmin/check-manifest/issues/57
1672 from check_manifest import check_manifest
1673
1674 # We need a Python interpeter to be in PATH.
1675 python = 'python'
1676 if hasattr(shutil, 'which'):
1677 for python in 'python', 'python3', os.path.basename(sys.executable):
1678 if shutil.which(python):
1679 break
1680 subdir = self._create_repo_with_code_in_subdir()
1681 self.assertTrue(check_manifest(subdir, python=python),
1682 sys.stderr.getvalue())
1683
1684 def test_extra_ignore(self):
1685 from check_manifest import IgnoreList, check_manifest
1686 self._create_repo_with_code()
1687 self._add_to_vcs('unrelated.txt')
1688 ignore = IgnoreList().global_exclude('*.txt')
1689 self.assertTrue(check_manifest(extra_ignore=ignore),
1690 sys.stderr.getvalue())
1691
1692 def test_suggestions(self):
1693 from check_manifest import check_manifest
1694 self._create_repo_with_code()
1695 self._add_to_vcs('unrelated.txt')
1696 self.assertFalse(check_manifest())
1697 self.assertIn("missing from sdist:\n unrelated.txt",
1698 sys.stderr.getvalue())
1699 self.assertIn("suggested MANIFEST.in rules:\n include *.txt",
1700 sys.stdout.getvalue())
1701
1702 def test_suggestions_create(self):
1703 from check_manifest import check_manifest
1704 self._create_repo_with_code()
1705 self._add_to_vcs('unrelated.txt')
1706 self.assertFalse(check_manifest(create=True))
1707 self.assertIn("missing from sdist:\n unrelated.txt",
1708 sys.stderr.getvalue())
1709 self.assertIn("suggested MANIFEST.in rules:\n include *.txt",
1710 sys.stdout.getvalue())
1711 self.assertIn("creating MANIFEST.in",
1712 sys.stdout.getvalue())
1713 with open('MANIFEST.in') as f:
1714 self.assertEqual(f.read(), "include *.txt\n")
1715
1716 def test_suggestions_update(self):
1717 from check_manifest import check_manifest
1718 self._create_repo_with_code()
1719 self._add_to_vcs('unrelated.txt')
1720 self._add_to_vcs('MANIFEST.in', '#tbd')
1721 self.assertFalse(check_manifest(update=True))
1722 self.assertIn("missing from sdist:\n unrelated.txt",
1723 sys.stderr.getvalue())
1724 self.assertIn("suggested MANIFEST.in rules:\n include *.txt",
1725 sys.stdout.getvalue())
1726 self.assertIn("updating MANIFEST.in",
1727 sys.stdout.getvalue())
1728 with open('MANIFEST.in') as f:
1729 self.assertEqual(
1730 f.read(),
1731 "#tbd\n# added by check-manifest\ninclude *.txt\n")
1732
1733 def test_suggestions_all_unknown_patterns(self):
1734 from check_manifest import check_manifest
1735 self._create_repo_with_code()
1736 self._add_to_vcs('.dunno-what-to-do-with-this')
1737 self.assertFalse(check_manifest(update=True))
1738 self.assertIn("missing from sdist:\n .dunno-what-to-do-with-this",
1739 sys.stderr.getvalue())
1740 self.assertIn(
1741 "don't know how to come up with rules matching any of the files, sorry!",
1742 sys.stdout.getvalue())
1743
1744 def test_suggestions_some_unknown_patterns(self):
1745 from check_manifest import check_manifest
1746 self._create_repo_with_code()
1747 self._add_to_vcs('.dunno-what-to-do-with-this')
1748 self._add_to_vcs('unrelated.txt')
1749 self.assertFalse(check_manifest(update=True))
1750 self.assertIn(
1751 "don't know how to come up with rules matching\n .dunno-what-to-do-with-this",
1752 sys.stdout.getvalue())
1753 self.assertIn("creating MANIFEST.in",
1754 sys.stdout.getvalue())
1755 with open('MANIFEST.in') as f:
1756 self.assertEqual(f.read(), "include *.txt\n")
1757
1758 def test_MANIFEST_in_does_not_need_to_be_added_to_be_considered(self):
1759 from check_manifest import check_manifest
1760 self._create_repo_with_code()
1761 self._add_to_vcs('unrelated.txt')
1762 with open('MANIFEST.in', 'w') as f:
1763 f.write("include *.txt\n")
1764 self.assertFalse(check_manifest())
1765 self.assertIn("missing from VCS:\n MANIFEST.in", sys.stderr.getvalue())
1766 self.assertNotIn("missing from sdist", sys.stderr.getvalue())
1767
1768 def test_setup_py_does_not_need_to_be_added_to_be_considered(self):
1769 from check_manifest import check_manifest
1770 self._create_repo_with_code(add_to_vcs=False)
1771 self._add_to_vcs('sample.py')
1772 self.assertFalse(check_manifest())
1773 self.assertIn("missing from VCS:\n setup.py", sys.stderr.getvalue())
1774 self.assertNotIn("missing from sdist", sys.stderr.getvalue())
1775
1776 def test_bad_ideas(self):
1777 from check_manifest import check_manifest
1778 self._create_repo_with_code()
1779 self._add_to_vcs('foo.egg-info')
1780 self._add_to_vcs('moo.mo')
1781 self.assertFalse(check_manifest())
1782 self.assertIn("you have foo.egg-info in source control!",
1783 sys.stderr.getvalue())
1784 self.assertIn("this also applies to the following:\n moo.mo",
1785 sys.stderr.getvalue())
1786
1787 def test_ignore_bad_ideas(self):
1788 from check_manifest import IgnoreList, check_manifest
1789 self._create_repo_with_code()
1790 with open('setup.cfg', 'w') as f:
1791 f.write('[check-manifest]\n'
1792 'ignore =\n'
1793 ' subdir/bar.egg-info\n'
1794 'ignore-bad-ideas =\n'
1795 ' subdir/bar.egg-info\n')
1796 self._add_to_vcs('foo.egg-info')
1797 self._add_to_vcs('moo.mo')
1798 self._add_to_vcs(os.path.join('subdir', 'bar.egg-info'))
1799 ignore = IgnoreList().global_exclude('*.mo')
1800 self.assertFalse(check_manifest(extra_ignore_bad_ideas=ignore))
1801 self.assertIn("you have foo.egg-info in source control!",
1802 sys.stderr.getvalue())
1803 self.assertNotIn("moo.mo", sys.stderr.getvalue())
1804 self.assertNotIn("bar.egg-info", sys.stderr.getvalue())
1805
1806 def test_missing_source_files(self):
1807 # https://github.com/mgedmin/check-manifest/issues/32
1808 from check_manifest import check_manifest
1809 self._create_repo_with_code()
1810 self._add_to_vcs('missing.py')
1811 os.unlink('missing.py')
1812 check_manifest()
1813 if self._vcs.command != 'bzr':
1814 # 'bzr ls' doesn't list files that were deleted but not
1815 # marked for deletion. 'bzr st' does, but it doesn't list
1816 # unmodified files. Importing bzrlib and using the API to
1817 # get the file list we need is (a) complicated, (b) opens
1818 # the optional dependency can of worms, and (c) not viable
1819 # under Python 3 unless we fork off a Python 2 subprocess.
1820 # Manually combining 'bzr ls' and 'bzr st' outputs just to
1821 # produce a cosmetic warning message seems like overkill.
1822 self.assertIn(
1823 "some files listed as being under source control are missing:\n"
1824 " missing.py",
1825 sys.stderr.getvalue())