Debian Codegraph @

tests/test_01_util.py

raw
1 """
2 This script tests utility functions.
3 """
4
5 import errno
6 import os
7 import os.path
8 import shutil
9 import tempfile
10 import unittest
11 from collections.abc import (
12 Iterable)
13 from functools import (
14 partial)
15 from pathlib import (
16 Path,
17 PurePath)
18 from typing import (
19 ClassVar,
20 Optional) # Replaced by `X | None` in 3.10.
21
22 from pathspec.patterns.gitignore.basic import (
23 GitIgnoreBasicPattern)
24 from pathspec.util import (
25 RecursionError,
26 check_match_file,
27 iter_tree_entries,
28 iter_tree_files,
29 match_file,
30 normalize_file)
31 from tests.util import (
32 get_paths_from_entries,
33 make_dirs,
34 make_files,
35 make_links,
36 mkfile,
37 ospath)
38
39
40 class CheckMatchFileTest(unittest.TestCase):
41 """
42 The :class:`CheckMatchFileTest` class tests the :meth:`.check_match_file`
43 function.
44 """
45
46 def test_01_single_1_include(self):
47 """
48 Test checking a single file that is included.
49 """
50 patterns = list(enumerate(map(GitIgnoreBasicPattern, [
51 "*.txt",
52 "!test/",
53 ])))
54
55 include_index = check_match_file(patterns, "include.txt")
56
57 self.assertEqual(include_index, (True, 0))
58
59 def test_01_single_2_exclude(self):
60 """
61 Test checking a single file that is excluded.
62 """
63 patterns = list(enumerate(map(GitIgnoreBasicPattern, [
64 "*.txt",
65 "!test/",
66 ])))
67
68 include_index = check_match_file(patterns, "test/exclude.txt")
69
70 self.assertEqual(include_index, (False, 1))
71
72 def test_01_single_3_unmatch(self):
73 """
74 Test checking a single file that is ignored.
75 """
76 patterns = list(enumerate(map(GitIgnoreBasicPattern, [
77 "*.txt",
78 "!test/",
79 ])))
80
81 include_index = check_match_file(patterns, "unmatch.bin")
82
83 self.assertEqual(include_index, (None, None))
84
85 def test_02_many(self):
86 """
87 Test matching files individually.
88 """
89 patterns = list(enumerate(map(GitIgnoreBasicPattern, [
90 '*.txt',
91 '!b.txt',
92 ])))
93 files = {
94 'X/a.txt',
95 'X/b.txt',
96 'X/Z/c.txt',
97 'Y/a.txt',
98 'Y/b.txt',
99 'Y/Z/c.txt',
100 }
101
102 includes = {
103 __file
104 for __file in files
105 if check_match_file(patterns, __file)[0]
106 }
107
108 self.assertEqual(includes, {
109 'X/a.txt',
110 'X/Z/c.txt',
111 'Y/a.txt',
112 'Y/Z/c.txt',
113 })
114
115
116 class IterTreeTest(unittest.TestCase):
117 """
118 The :class:`IterTreeTest` class tests :meth:`.iter_tree_entries` and
119 :meth:`.iter_tree_files` functions.
120 """
121
122 no_symlink: ClassVar[bool]
123 """
124 *no_symlink* (:class:`bool`) is whether symlinks are not supported.
125 """
126
127 def make_dirs(self, dirs: Iterable[str]) -> None:
128 """
129 Create the specified directories.
130 """
131 make_dirs(self.temp_dir, dirs)
132
133 def make_files(self, files: Iterable[str]) -> None:
134 """
135 Create the specified files.
136 """
137 make_files(self.temp_dir, files)
138
139 def make_links(self, links: Iterable[tuple[str, str]]) -> None:
140 """
141 Create the specified links.
142 """
143 make_links(self.temp_dir, links)
144
145 def require_symlink(self) -> None:
146 """
147 Skips the test if `os.symlink` is not supported.
148 """
149 if self.no_symlink:
150 raise unittest.SkipTest("`os.symlink` is not supported.")
151
152 def setUp(self) -> None:
153 """
154 Called before each test.
155 """
156 self.temp_dir = Path(tempfile.mkdtemp())
157
158 def tearDown(self) -> None:
159 """
160 Called after each test.
161 """
162 shutil.rmtree(self.temp_dir)
163
164 def test_01_files_1_entries(self):
165 """
166 Tests to make sure all files are found.
167 """
168 self.make_dirs([
169 'Empty',
170 'Dir',
171 'Dir/Inner',
172 ])
173 self.make_files([
174 'a',
175 'b',
176 'Dir/c',
177 'Dir/d',
178 'Dir/Inner/e',
179 'Dir/Inner/f',
180 ])
181 results = get_paths_from_entries(iter_tree_entries(self.temp_dir))
182 self.assertEqual(results, set(map(ospath, [
183 'a',
184 'b',
185 'Dir',
186 'Dir/Inner',
187 'Dir/Inner/e',
188 'Dir/Inner/f',
189 'Dir/c',
190 'Dir/d',
191 'Empty',
192 ])))
193
194 def test_01_files_2_files(self):
195 """
196 Tests to make sure all files are found.
197 """
198 self.make_dirs([
199 'Empty',
200 'Dir',
201 'Dir/Inner',
202 ])
203 self.make_files([
204 'a',
205 'b',
206 'Dir/c',
207 'Dir/d',
208 'Dir/Inner/e',
209 'Dir/Inner/f',
210 ])
211 results = set(iter_tree_files(self.temp_dir))
212 self.assertEqual(results, set(map(ospath, [
213 'a',
214 'b',
215 'Dir/c',
216 'Dir/d',
217 'Dir/Inner/e',
218 'Dir/Inner/f',
219 ])))
220
221 def test_02_link_1_check_symlink(self):
222 """
223 Tests whether links can be created.
224 """
225 # NOTE: Windows Vista and greater supports `os.symlink` for Python 3.2+.
226 no_symlink: Optional[bool] = None
227 try:
228 file = self.temp_dir / 'file'
229 link = self.temp_dir / 'link'
230 mkfile(file)
231
232 try:
233 os.symlink(file, link)
234 except (AttributeError, NotImplementedError, OSError):
235 no_symlink = True
236 else:
237 no_symlink = False
238
239 finally:
240 self.__class__.no_symlink = no_symlink
241
242 def test_02_link_2_links_1_entries(self):
243 """
244 Tests to make sure links to directories and files work.
245 """
246 self.require_symlink()
247 self.make_dirs([
248 'Dir',
249 ])
250 self.make_files([
251 'a',
252 'b',
253 'Dir/c',
254 'Dir/d',
255 ])
256 self.make_links([
257 ('ax', 'a'),
258 ('bx', 'b'),
259 ('Dir/cx', 'Dir/c'),
260 ('Dir/dx', 'Dir/d'),
261 ('DirX', 'Dir'),
262 ])
263 results = get_paths_from_entries(iter_tree_entries(self.temp_dir))
264 self.assertEqual(results, set(map(ospath, [
265 'a',
266 'ax',
267 'b',
268 'bx',
269 'Dir',
270 'Dir/c',
271 'Dir/cx',
272 'Dir/d',
273 'Dir/dx',
274 'DirX',
275 'DirX/c',
276 'DirX/cx',
277 'DirX/d',
278 'DirX/dx',
279 ])))
280
281 def test_02_link_2_links_2_files(self):
282 """
283 Tests to make sure links to directories and files work.
284 """
285 self.require_symlink()
286 self.make_dirs([
287 'Dir',
288 ])
289 self.make_files([
290 'a',
291 'b',
292 'Dir/c',
293 'Dir/d',
294 ])
295 self.make_links([
296 ('ax', 'a'),
297 ('bx', 'b'),
298 ('Dir/cx', 'Dir/c'),
299 ('Dir/dx', 'Dir/d'),
300 ('DirX', 'Dir'),
301 ])
302 results = set(iter_tree_files(self.temp_dir))
303 self.assertEqual(results, set(map(ospath, [
304 'a',
305 'ax',
306 'b',
307 'bx',
308 'Dir/c',
309 'Dir/cx',
310 'Dir/d',
311 'Dir/dx',
312 'DirX/c',
313 'DirX/cx',
314 'DirX/d',
315 'DirX/dx',
316 ])))
317
318 def test_02_link_3_sideways_links_1_entries(self):
319 """
320 Tests to make sure the same directory can be encountered multiple
321 times via links.
322 """
323 self.require_symlink()
324 self.make_dirs([
325 'Dir',
326 'Dir/Target',
327 ])
328 self.make_files([
329 'Dir/Target/file',
330 ])
331 self.make_links([
332 ('Ax', 'Dir'),
333 ('Bx', 'Dir'),
334 ('Cx', 'Dir/Target'),
335 ('Dx', 'Dir/Target'),
336 ('Dir/Ex', 'Dir/Target'),
337 ('Dir/Fx', 'Dir/Target'),
338 ])
339 results = get_paths_from_entries(iter_tree_entries(self.temp_dir))
340 self.assertEqual(results, set(map(ospath, [
341 'Ax',
342 'Ax/Ex',
343 'Ax/Ex/file',
344 'Ax/Fx',
345 'Ax/Fx/file',
346 'Ax/Target',
347 'Ax/Target/file',
348 'Bx',
349 'Bx/Ex',
350 'Bx/Ex/file',
351 'Bx/Fx',
352 'Bx/Fx/file',
353 'Bx/Target',
354 'Bx/Target/file',
355 'Cx',
356 'Cx/file',
357 'Dx',
358 'Dx/file',
359 'Dir',
360 'Dir/Ex',
361 'Dir/Ex/file',
362 'Dir/Fx',
363 'Dir/Fx/file',
364 'Dir/Target',
365 'Dir/Target/file',
366 ])))
367
368 def test_02_link_3_sideways_links_2_files(self):
369 """
370 Tests to make sure the same directory can be encountered multiple
371 times via links.
372 """
373 self.require_symlink()
374 self.make_dirs([
375 'Dir',
376 'Dir/Target',
377 ])
378 self.make_files([
379 'Dir/Target/file',
380 ])
381 self.make_links([
382 ('Ax', 'Dir'),
383 ('Bx', 'Dir'),
384 ('Cx', 'Dir/Target'),
385 ('Dx', 'Dir/Target'),
386 ('Dir/Ex', 'Dir/Target'),
387 ('Dir/Fx', 'Dir/Target'),
388 ])
389 results = set(iter_tree_files(self.temp_dir))
390 self.assertEqual(results, set(map(ospath, [
391 'Ax/Ex/file',
392 'Ax/Fx/file',
393 'Ax/Target/file',
394 'Bx/Ex/file',
395 'Bx/Fx/file',
396 'Bx/Target/file',
397 'Cx/file',
398 'Dx/file',
399 'Dir/Ex/file',
400 'Dir/Fx/file',
401 'Dir/Target/file',
402 ])))
403
404 def test_02_link_4_recursive_links_1_entries(self):
405 """
406 Tests detection of recursive links.
407 """
408 self.require_symlink()
409 self.make_dirs([
410 'Dir',
411 ])
412 self.make_files([
413 'Dir/file',
414 ])
415 self.make_links([
416 ('Dir/Self', 'Dir'),
417 ])
418 with self.assertRaises(RecursionError) as context:
419 set(iter_tree_entries(self.temp_dir))
420
421 self.assertEqual(context.exception.first_path, 'Dir')
422 self.assertEqual(context.exception.second_path, ospath('Dir/Self'))
423
424 def test_02_link_4_recursive_links_2_files(self):
425 """
426 Tests detection of recursive links.
427 """
428 self.require_symlink()
429 self.make_dirs([
430 'Dir',
431 ])
432 self.make_files([
433 'Dir/file',
434 ])
435 self.make_links([
436 ('Dir/Self', 'Dir'),
437 ])
438 with self.assertRaises(RecursionError) as context:
439 set(iter_tree_files(self.temp_dir))
440
441 self.assertEqual(context.exception.first_path, 'Dir')
442 self.assertEqual(context.exception.second_path, ospath('Dir/Self'))
443
444 def test_02_link_5_recursive_circular_links_1_entries(self):
445 """
446 Tests detection of recursion through circular links.
447 """
448 self.require_symlink()
449 self.make_dirs([
450 'A',
451 'B',
452 'C',
453 ])
454 self.make_files([
455 'A/d',
456 'B/e',
457 'C/f',
458 ])
459 self.make_links([
460 ('A/Bx', 'B'),
461 ('B/Cx', 'C'),
462 ('C/Ax', 'A'),
463 ])
464 with self.assertRaises(RecursionError) as context:
465 set(iter_tree_entries(self.temp_dir))
466
467 self.assertIn(context.exception.first_path, ('A', 'B', 'C'))
468 self.assertEqual(context.exception.second_path, {
469 'A': ospath('A/Bx/Cx/Ax'),
470 'B': ospath('B/Cx/Ax/Bx'),
471 'C': ospath('C/Ax/Bx/Cx'),
472 }[context.exception.first_path])
473
474 def test_02_link_5_recursive_circular_links_2_files(self):
475 """
476 Tests detection of recursion through circular links.
477 """
478 self.require_symlink()
479 self.make_dirs([
480 'A',
481 'B',
482 'C',
483 ])
484 self.make_files([
485 'A/d',
486 'B/e',
487 'C/f',
488 ])
489 self.make_links([
490 ('A/Bx', 'B'),
491 ('B/Cx', 'C'),
492 ('C/Ax', 'A'),
493 ])
494 with self.assertRaises(RecursionError) as context:
495 set(iter_tree_files(self.temp_dir))
496
497 self.assertIn(context.exception.first_path, ('A', 'B', 'C'))
498 self.assertEqual(context.exception.second_path, {
499 'A': ospath('A/Bx/Cx/Ax'),
500 'B': ospath('B/Cx/Ax/Bx'),
501 'C': ospath('C/Ax/Bx/Cx'),
502 }[context.exception.first_path])
503
504 def test_02_link_6_detect_broken_links_1_entries(self):
505 """
506 Tests that broken links are detected.
507 """
508 def reraise(e):
509 raise e
510
511 self.require_symlink()
512 self.make_links([
513 ('A', 'DOES_NOT_EXIST'),
514 ])
515 with self.assertRaises(OSError) as context:
516 set(iter_tree_entries(self.temp_dir, on_error=reraise))
517
518 self.assertEqual(context.exception.errno, errno.ENOENT)
519
520 def test_02_link_6_detect_broken_links_2_files(self):
521 """
522 Tests that broken links are detected.
523 """
524 def reraise(e):
525 raise e
526
527 self.require_symlink()
528 self.make_links([
529 ('A', 'DOES_NOT_EXIST'),
530 ])
531 # `iter_tree_files` does not stat the link.
532 set(iter_tree_files(self.temp_dir, on_error=reraise))
533
534 def test_02_link_7_ignore_broken_links_1_entries(self):
535 """
536 Tests that broken links are ignored.
537 """
538 self.require_symlink()
539 self.make_links([
540 ('A', 'DOES_NOT_EXIST'),
541 ])
542 results = get_paths_from_entries(iter_tree_entries(self.temp_dir))
543 self.assertEqual(results, set())
544
545 def test_02_link_7_ignore_broken_links_2_files(self):
546 """
547 Tests that broken links are ignored.
548 """
549 self.require_symlink()
550 self.make_links([
551 ('A', 'DOES_NOT_EXIST'),
552 ])
553 results = set(iter_tree_files(self.temp_dir))
554 self.assertEqual(results, set())
555
556 def test_02_link_8_no_follow_links_1_entries(self):
557 """
558 Tests to make sure directory links can be ignored.
559 """
560 self.require_symlink()
561 self.make_dirs([
562 'Dir',
563 ])
564 self.make_files([
565 'A',
566 'B',
567 'Dir/C',
568 'Dir/D',
569 ])
570 self.make_links([
571 ('Ax', 'A'),
572 ('Bx', 'B'),
573 ('Dir/Cx', 'Dir/C'),
574 ('Dir/Dx', 'Dir/D'),
575 ('DirX', 'Dir'),
576 ])
577 results = get_paths_from_entries(iter_tree_entries(self.temp_dir, follow_links=False))
578 self.assertEqual(results, set(map(ospath, [
579 'A',
580 'Ax',
581 'B',
582 'Bx',
583 'Dir',
584 'Dir/C',
585 'Dir/Cx',
586 'Dir/D',
587 'Dir/Dx',
588 'DirX',
589 ])))
590
591 def test_02_link_8_no_follow_links_2_files(self):
592 """
593 Tests to make sure directory links can be ignored.
594 """
595 self.require_symlink()
596 self.make_dirs([
597 'Dir',
598 ])
599 self.make_files([
600 'A',
601 'B',
602 'Dir/C',
603 'Dir/D',
604 ])
605 self.make_links([
606 ('Ax', 'A'),
607 ('Bx', 'B'),
608 ('Dir/Cx', 'Dir/C'),
609 ('Dir/Dx', 'Dir/D'),
610 ('DirX', 'Dir'),
611 ])
612 results = set(iter_tree_files(self.temp_dir, follow_links=False))
613 self.assertEqual(results, set(map(ospath, [
614 'A',
615 'Ax',
616 'B',
617 'Bx',
618 'Dir/C',
619 'Dir/Cx',
620 'Dir/D',
621 'Dir/Dx',
622 'DirX',
623 ])))
624
625
626 class MatchFileTest(unittest.TestCase):
627 """
628 The :class:`MatchFileTest` class tests the :meth:`.match_file`
629 function.
630 """
631
632 def test_01_single_1_include(self):
633 """
634 Test checking a single file that is included.
635 """
636 patterns = list(map(GitIgnoreBasicPattern, [
637 "*.txt",
638 "!test/",
639 ]))
640
641 include = match_file(patterns, "include.txt")
642
643 self.assertIs(include, True)
644
645 def test_01_single_2_exclude(self):
646 """
647 Test checking a single file that is excluded.
648 """
649 patterns = list(map(GitIgnoreBasicPattern, [
650 "*.txt",
651 "!test/",
652 ]))
653
654 include = match_file(patterns, "test/exclude.txt")
655
656 self.assertIs(include, False)
657
658 def test_01_single_3_unmatch(self):
659 """
660 Test checking a single file that is ignored.
661 """
662 patterns = list(map(GitIgnoreBasicPattern, [
663 "*.txt",
664 "!test/",
665 ]))
666
667 include = match_file(patterns, "unmatch.bin")
668
669 self.assertIs(include, False)
670
671 def test_02_many(self):
672 """
673 Test matching files individually.
674 """
675 patterns = list(map(GitIgnoreBasicPattern, [
676 '*.txt',
677 '!b.txt',
678 ]))
679 files = {
680 'X/a.txt',
681 'X/b.txt',
682 'X/Z/c.txt',
683 'Y/a.txt',
684 'Y/b.txt',
685 'Y/Z/c.txt',
686 }
687
688 includes = set(filter(partial(match_file, patterns), files))
689
690 self.assertEqual(includes, {
691 'X/a.txt',
692 'X/Z/c.txt',
693 'Y/a.txt',
694 'Y/Z/c.txt',
695 })
696
697
698 class NormalizeFileTest(unittest.TestCase):
699 """
700 The :class:`NormalizeFileTest` class tests the :meth:`.normalize_file`
701 function.
702 """
703
704 def test_01_purepath(self):
705 """
706 Tests normalizing a :class:`PurePath` as argument.
707 """
708 first_spec = normalize_file(PurePath('a.txt'))
709 second_spec = normalize_file('a.txt')
710 self.assertEqual(first_spec, second_spec)