Debian Codegraph @

tests/test_seedir.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Unit tests for seedir.
4
5 Previously written for unittests, and updated for pytest.
6
7 Test methods MUST start with "test"
8 """
9
10 import os
11
12 import pytest
13
14 import seedir as sd
15 from seedir.errors import FakedirError
16 from seedir.folderstructure import FakeDirStructure as FDS
17
18 # ---- Test seedir strings
19
20 example = """mypkg/
21 __init__.py
22 app.py
23 view.py
24 test/
25 __init__.py
26 test_app.py
27 test_view.py"""
28
29 no_init = """mypkg/
30 app.py
31 view.py
32 test/
33 test_app.py
34 test_view.py"""
35
36 example_with_comments="""mypkg/
37 __init__.py #some comments
38 app.py ##### more comments
39 view.py #how about## this one
40 test/
41 __init__.py
42 test_app.py
43 test_view.py"""
44
45 # sd.randomdir(seed=456)
46 large_example = """MyFakeDir/
47 ├─Vogel.txt
48 ├─monkish.txt
49 ├─jowly.txt
50 ├─scrooge/
51 │ ├─light.txt
52 │ ├─reliquary.txt
53 │ ├─sandal/
54 │ ├─paycheck/
55 │ │ ├─electrophoresis.txt
56 │ │ └─Pyongyang/
57 │ └─patrimonial/
58 ├─Uganda/
59 └─pedantic/
60 └─cataclysmic.txt"""
61
62 large_example_access_denied = """MyFakeDir/
63 ├─Vogel.txt
64 ├─monkish.txt
65 ├─jowly.txt
66 ├─scrooge/ [ACCESS DENIED]
67 ├─Uganda/ [ACCESS DENIED]
68 └─pedantic/ [ACCESS DENIED]"""
69
70 large_example_bummer = """MyFakeDir/
71 ├─Vogel.txt
72 ├─monkish.txt
73 ├─jowly.txt
74 ├─scrooge/<- BUMMER!
75 ├─Uganda/<- BUMMER!
76 └─pedantic/<- BUMMER!"""
77
78 limit0_nobeyond = 'MyFakeDir/'
79
80 limit0_beyond_content = """MyFakeDir/
81 └─3 folder(s), 3 file(s)"""
82
83 depthlimit1 = '''MyFakeDir/
84 ├─Vogel.txt
85 ├─monkish.txt
86 ├─jowly.txt
87 ├─scrooge/
88 ├─Uganda/
89 └─pedantic/'''
90
91 depthlimit1_beyond_content = '''MyFakeDir/
92 ├─Vogel.txt
93 ├─monkish.txt
94 ├─jowly.txt
95 ├─scrooge/
96 │ └─3 folder(s), 2 file(s)
97 ├─Uganda/
98 │ └─0 folder(s), 0 file(s)
99 └─pedantic/
100 └─0 folder(s), 1 file(s)'''
101
102 depthlimit1_beyond_content_exclude = '''MyFakeDir/
103 ├─scrooge/
104 │ └─3 folder(s), 0 file(s)
105 ├─Uganda/
106 │ └─0 folder(s), 0 file(s)
107 └─pedantic/
108 └─0 folder(s), 0 file(s)'''
109
110 complex_sort = '''MyFakeDir/
111 ├─monkish.txt
112 ├─Vogel.txt
113 ├─jowly.txt
114 ├─pedantic/
115 │ └─cataclysmic.txt
116 ├─scrooge/
117 │ ├─reliquary.txt
118 │ ├─light.txt
119 │ ├─patrimonial/
120 │ ├─paycheck/
121 │ │ ├─electrophoresis.txt
122 │ │ └─Pyongyang/
123 │ └─sandal/
124 └─Uganda/'''
125
126 complex_inclusion = '''MyFakeDir/
127 ├─Vogel.txt
128 ├─monkish.txt
129 ├─jowly.txt
130 ├─scrooge/
131 │ ├─light.txt
132 │ └─sandal/
133 └─pedantic/'''
134
135 fmt_expand_single = '''MyFakeDir/
136 ├─Vogel.txt
137 ├─monkish.txt
138 ├─jowly.txt
139 ├─scrooge/
140 │ ├─light.txt
141 │ ├─reliquary.txt
142 │ ├─sandal/
143 │ ├─paycheck/
144 │ │ ├─electrophoresis.txt
145 │ │ └─Pyongyang/
146 │ └─patrimonial/
147 ├─Uganda/
148 └─pedantic/'''
149
150 fmt_expand_single_partial = '''MyFakeDir/
151 ├─Vogel.txt
152 ├─monkish.txt
153 ├─jowly.txt
154 ├─scrooge/
155 │ ├─light.txt
156 │ ├─reliquary.txt
157 │ ├─sandal/
158 │ ├─paycheck/
159 │ └─patrimonial/
160 ├─Uganda/
161 └─pedantic/'''
162
163 fmt_notbeyond = """MyFakeDir/
164 ->Vogel.txt
165 └─3 folder(s), 2 file(s)"""
166
167 fmt_with_mask = '''MyFakeDir/
168 ├─scrooge/
169 │ ├─light.txt
170 │ └─reliquary.txt
171 ├─Uganda/
172 └─pedantic/
173 └─cataclysmic.txt'''
174
175 # variables
176 styles = ['lines', 'dash', 'spaces', 'arrow', 'plus', 'emoji']
177 try:
178 import emoji
179 except ImportError:
180 styles.remove('emoji')
181
182 # realdir for testing on
183 testdir = os.path.dirname(os.path.abspath(__file__))
184
185 # custom FakeDirStructure for testing errors
186 class ErrorRaisingFDS(FDS):
187
188 def listdir(self, item):
189 if self.isdir(item) and item.depth != 0:
190 raise FakedirError('Oops!!!')
191 else:
192 return item.listdir()
193
194 # ---- Test cases
195
196 class PrintSomeDirs:
197
198 print('\n--------------------'
199 '\n\nTesting seedir.seedir() against {}:\n\n'
200 '--------------------'
201 '\n'.format(testdir))
202 def test_a_print_userprofile(self):
203 print('Basic seedir (depthlimit=2, itemlimit=10):\n')
204 sd.seedir(testdir, depthlimit=2, itemlimit=10)
205
206 def test_b_styles(self):
207 print('\nDifferent Styles (depthlimit=1, itemlimit=5):')
208 for style in sd.STYLE_DICT.keys():
209 print('\n{}:\n'.format(style))
210 sd.seedir(testdir, style=style, depthlimit=1, itemlimit=5)
211
212 def test_c_custom_styles(self):
213 print('\nCustom Styles (depthlimit=1, itemlimit=5):')
214 sd.seedir(testdir, depthlimit=1, itemlimit=5, space='>>',
215 split='>>', extend='II', final='->',
216 folderstart='Folder: ', filestart='File: ')
217
218 def test_d_indent(self):
219 print('\nDifferent Indents (depthlimit=1, itemlimit=5):')
220 for i in list(range(3)) + [8]:
221 print('\nindent={}:\n'.format(str(i)))
222 sd.seedir(testdir, depthlimit=1, itemlimit=5, indent=i)
223
224 def test_e_beyond(self):
225 print('\nItems Beyond Limit (depthlimit=1, itemlimit=1, beyond="content")')
226 sd.seedir(testdir, itemlimit=1, beyond='content')
227
228 def test_improper_kwargs(self):
229 with pytest.raises(ValueError):
230 sd.seedir(testdir, spacing=False)
231
232 class TestSeedirStringFormatting:
233 def test_get_base_header_0(self):
234 a = '| '
235 b = ' '
236 assert FDS().get_base_header([0], a, b) == ''
237
238 def test_get_base_header_013(self):
239 a = '| '
240 b = ' '
241 assert FDS().get_base_header([0, 1, 3], a, b) == '| | '
242
243 def test_get_base_header_empty(self):
244 a = '| '
245 b = ' '
246 assert FDS().get_base_header([], a, b) == ''
247
248 def test_STYLE_DICT_members(self):
249 keys = set(sd.STYLE_DICT.keys())
250 assert keys == set(styles)
251
252 @pytest.mark.parametrize('style', styles)
253 def test_get_style_args_all_accessible(self, style):
254 d = sd.get_styleargs(style)
255 assert isinstance(d, dict)
256
257 def test_access_missing_style(self):
258 with pytest.raises(ValueError):
259 _ = sd.get_styleargs('missing_style')
260
261 def test_get_style_args_deepcopy(self):
262 x = sd.STYLE_DICT['lines']
263 y = sd.get_styleargs('lines')
264 assert x is not y
265
266 def test_format_indent_4(self):
267 a = sd.get_styleargs('lines')
268 sd.printing.format_indent(a, indent=4)
269 chars = ['extend', 'space', 'split', 'final']
270 assert all(len(a[c])==4 for c in chars)
271
272 def test_format_indent_1(self):
273 a = sd.get_styleargs('lines')
274 sd.printing.format_indent(a, indent=1)
275 chars = ['extend', 'space', 'split', 'final']
276 assert all(len(a[c])==1 for c in chars)
277
278 def test_words_list_start(self):
279 assert sd.printing.words[0] == 'a'
280
281 def test_words_list_length(self):
282 assert len(sd.printing.words) == 25487
283
284 class TestFakeDirReading:
285 def test_read_string(self):
286 x = sd.fakedir_fromstring(example)
287 assert isinstance(x, sd.FakeDir)
288
289 def test_parse_comments_on(self):
290 x = sd.fakedir_fromstring(example)
291 y = sd.fakedir_fromstring(example_with_comments)
292 assert x.get_child_names() == y.get_child_names()
293
294 def test_parse_comments_off(self):
295 x = sd.fakedir_fromstring(example)
296 y = sd.fakedir_fromstring(example_with_comments, parse_comments=False)
297 assert x.get_child_names() != y.get_child_names()
298
299 class TestFakeDir:
300 def test_count_fake_folders(self):
301 x = sd.fakedir_fromstring(example)
302 assert FDS().count_folders(x.listdir()) == 1
303
304 def test_count_fake_files(self):
305 x = sd.fakedir_fromstring(example)
306 assert FDS().count_files(x.listdir()) == 3
307
308 def test_sort_fakedir(self):
309 x = sd.fakedir_fromstring(example).listdir()
310 sort = FDS().sort_dir(x, sort_reverse=True, sort_key=lambda x : x[1])
311 sort = [f.name for f in sort]
312 correct = ['app.py', 'view.py', 'test', '__init__.py']
313 assert sort == correct
314
315 def test_exclude_files_and_reread(self):
316 x = sd.fakedir_fromstring(example)
317 y = x.seedir(printout=False, exclude_files=r'.*\..*', regex=True)
318 z = sd.fakedir_fromstring(y)
319 assert set(z.get_child_names()) == set(['test'])
320
321 def test_include_files_and_reread(self):
322 x = sd.fakedir_fromstring(example)
323 y = x.seedir(printout=False, include_files=['app.py', 'view.py'],
324 regex=False)
325 z = sd.fakedir_fromstring(y)
326 assert set(z.get_child_names()) == set(['app.py', 'view.py', 'test', ])
327
328 def test_delete_string_names(self):
329 x = sd.randomdir()
330 x.delete(x.get_child_names())
331 assert len(x.listdir()) == 0
332
333 def test_delete_objects(self):
334 x = sd.randomdir()
335 x.delete(x.listdir())
336 assert len(x.listdir()) == 0
337
338 def test_set_parent(self):
339 x = sd.fakedir_fromstring(example)
340 x['test/test_app.py'].parent = x
341 assert 'test_app.py' in x.get_child_names()
342
343 def test_walk_apply(self):
344 def add_0(f):
345 f.name += ' 0'
346 x = sd.fakedir_fromstring(example)
347 x.walk_apply(add_0)
348 last_chars = [f[-1] for f in x.get_child_names()]
349 assert set(last_chars) == set('0')
350
351 def test_depth_setting(self):
352 x = sd.fakedir_fromstring(example)
353 x['test'].create_folder('A')
354 x['test/A'].create_folder('B')
355 x['test/A/B'].create_file('boris.txt')
356 obj = x['test/A/B/boris.txt']
357 depth_a = obj.depth
358 obj.parent = x
359 depth_b = obj.depth
360 assert (depth_a, depth_b) == (4, 1)
361
362 def test_randomdir_seed(self):
363 x = sd.randomdir(seed=4.21)
364 y = sd.randomdir(seed=4.21)
365 assert x.get_child_names() == y.get_child_names()
366
367 def test_empty_fakedir_has_no_children(self):
368 x = sd.FakeDir('BORIS')
369 assert len(x.get_child_names()) == 0
370
371 def test_populate_adds_children(self):
372 x = sd.FakeDir('BORIS')
373 sd.populate(x)
374 assert len(x.get_child_names()) > 0
375
376 def test_copy_equal(self):
377 x = sd.randomdir(seed=7)
378 y = x.copy()
379 assert x.seedir(printout=False) == y.seedir(printout=False)
380
381 def test_copy_unlinked(self):
382 def pallindrome(f):
383 f.name = f.name + f.name[::-1]
384 x = sd.fakedir_fromstring(large_example)
385
386 before = x.seedir(printout=False)
387
388 y = x.copy()
389 y.walk_apply(pallindrome)
390
391 after = x.seedir(printout=False)
392 assert before == after
393
394 class TestMask:
395 def test_mask_no_folders_or_files(self):
396 def foo(x):
397 if os.path.isdir(x) or os.path.isfile(x):
398 return False
399
400 s = sd.seedir(testdir, printout=False, depthlimit=2, itemlimit=10, mask=foo,)
401 s = s.split('\n')
402 assert len(s) == 1
403
404 def test_mask_always_false(self):
405 def bar(x):
406 return False
407 s = sd.seedir(testdir, printout=False, depthlimit=2, itemlimit=10, mask=bar)
408 s = s.split('\n')
409 assert len(s) == 1
410
411 def test_mask_fakedir_fromstring(self):
412 x = sd.fakedir_fromstring(example)
413 s = x.seedir(printout=False, mask=lambda x : not x.name[0] == '_',
414 style='spaces', indent=4)
415 assert no_init == s
416
417 def test_mask_fakedir(self):
418 def foo(x):
419 if os.path.isdir(x) or os.path.isfile(x):
420 return False
421 f = sd.fakedir(testdir, mask=foo)
422 assert len(f.listdir()) == 0
423
424 class TestFolderStructure:
425
426 def test_many_randomdirs(self):
427 seeds = range(1000)
428 results = []
429 for i in seeds:
430 r = sd.randomdir(seed=i)
431 s = r.seedir(printout=False)
432 f = sd.fakedir_fromstring(s)
433 results.append(s == f.seedir(printout=False))
434 assert all(results)
435
436 def test_itemlimit0_nobeyond(self):
437 ans = limit0_nobeyond
438 f = sd.fakedir_fromstring(large_example)
439 s = f.seedir(printout=False, itemlimit=0)
440 assert ans == s
441
442 def test_depthlimit0_nobeyond(self):
443 ans = limit0_nobeyond
444 f = sd.fakedir_fromstring(large_example)
445 s = f.seedir(printout=False, depthlimit=0)
446 assert ans == s
447
448 def test_itemlimit0_beyond_content(self):
449 ans = limit0_beyond_content
450 f = sd.fakedir_fromstring(large_example)
451 s = f.seedir(printout=False, itemlimit=0, beyond='content')
452 assert ans == s
453
454 def test_depthlimit0_beyond_content(self):
455 ans = limit0_beyond_content
456 f = sd.fakedir_fromstring(large_example)
457 s = f.seedir(printout=False, depthlimit=0, beyond='content')
458 assert ans == s
459
460 def test_depthlimit1(self):
461 ans = depthlimit1
462 f = sd.fakedir_fromstring(large_example)
463 s = f.seedir(printout=False, depthlimit=1)
464 assert ans == s
465
466 def test_depthlimit1_beyond_content(self):
467 ans = depthlimit1_beyond_content
468 f = sd.fakedir_fromstring(large_example)
469 s = f.seedir(printout=False, depthlimit=1, beyond='content')
470 assert ans == s
471
472 def test_depthlimit1_beyond_content_exclude(self):
473 ans = depthlimit1_beyond_content_exclude
474 f = sd.fakedir_fromstring(large_example)
475 s = f.seedir(printout=False,
476 depthlimit=1,
477 beyond='content',
478 exclude_files=r'.*\.txt',
479 regex=True)
480 assert ans == s
481
482 def test_complex_sort(self):
483 ans = complex_sort
484 params = dict(sort=True, sort_reverse=True,
485 sort_key = lambda x: len(x), first='files')
486 f = sd.fakedir_fromstring(large_example)
487 s = f.seedir(printout=False,**params)
488 assert ans == s
489
490 def test_complex_inclusion(self):
491 ans = complex_inclusion
492 params = dict(include_folders=['sandal', 'scrooge', 'pedantic'],
493 exclude_folders='sandal',
494 exclude_files='^Vogel',
495 include_files='^.[oi]',
496 regex=True)
497 f = sd.fakedir_fromstring(large_example)
498 s = f.seedir(printout=False,**params)
499 assert ans == s
500
501 class TestFormatter:
502
503 def test_formatter_beyond(self):
504
505 def fmt(p):
506
507 d = {'split':'->', 'final':'->'}
508
509 return d
510
511 ans = fmt_notbeyond
512 f = sd.fakedir_fromstring(large_example)
513 s = f.seedir(formatter=fmt, itemlimit=1, beyond='content', printout=False)
514 assert s == ans
515
516
517 def test_formatter_no_return(self):
518
519 f = sd.fakedir_fromstring(large_example)
520 s = f.seedir(formatter=lambda x: None, printout=False)
521 assert s == large_example
522
523 def test_expand_one_folder_sticky(self):
524
525 def fmt(p):
526
527 d = {}
528 if p.name == 'scrooge':
529 d['depthlimit'] = None
530
531 return d
532
533 ans = fmt_expand_single
534 f = sd.fakedir_fromstring(large_example)
535 s = f.seedir(formatter=fmt, depthlimit=1, sticky_formatter=True, printout=False)
536 assert ans == s
537
538 def test_expand_one_folder_nosticky(self):
539
540 def fmt(p):
541
542 d = {}
543 if p.name == 'scrooge':
544 d['depthlimit'] = None
545
546 return d
547
548 ans = fmt_expand_single_partial
549 f = sd.fakedir_fromstring(large_example)
550 s = f.seedir(formatter=fmt, depthlimit=1, printout=False)
551 assert ans == s
552
553 def test_mask_with_fmt(self):
554
555 def fmt(p):
556
557 d = {}
558
559 def case1(p):
560 return not p.name.endswith('.txt')
561
562 def case2(p):
563 return p.name.endswith('.txt')
564
565 if p.depth == 0:
566 d['mask'] = case1
567
568 else:
569 d['mask'] = case2
570
571 return d
572
573 ans = fmt_with_mask
574 f = sd.fakedir_fromstring(large_example)
575 s = f.seedir(formatter=fmt, printout=False)
576 assert s == ans
577
578 class TestTupleItemLimit:
579
580 def count_folder_children(self, f):
581 output = []
582 foo = lambda x: output.append(len([a for a in f.listdir() if a.isdir()]))
583 f.walk_apply(foo)
584 return output
585
586 def count_file_children(self, f):
587 output = []
588 foo = lambda x: output.append(len([a for a in f.listdir() if not a.isdir()]))
589 f.walk_apply(foo)
590 return output
591
592 def make_letter_example(self):
593 f = sd.FakeDir('example')
594 f.create_folder(['a', 'b', 'c', 'd'])
595 f.create_file(['e', 'f', 'g', 'h'])
596 return f
597
598 def test_None_None(self):
599 f = sd.fakedir_fromstring(large_example)
600 normal = f.seedir(printout=False)
601 test = f.seedir(itemlimit=(None, None), printout=False)
602 assert normal == test
603
604 def test_None_1(self):
605 start = sd.fakedir_fromstring(large_example)
606 s = start.seedir(itemlimit=(None, 1), first='files', printout=False)
607 end = sd.fakedir_fromstring(s)
608 ans = self.count_file_children(end)
609 assert all([x <= 1 for x in ans])
610
611 def test_1_None(self):
612 start = sd.fakedir_fromstring(large_example)
613 s = start.seedir(itemlimit=(1, None), first='folders', printout=False)
614 end = sd.fakedir_fromstring(s)
615 ans = self.count_folder_children(end)
616 assert all([x <= 1 for x in ans])
617
618 def test_1_1(self):
619 start = sd.fakedir_fromstring(large_example)
620 s = start.seedir(itemlimit=(1, None), first='folders', printout=False)
621 end = sd.fakedir_fromstring(s)
622 ans = self.count_folder_children(end)
623 assert all([x <= 1 for x in ans])
624
625 def test_filter_letter_example_2_2(self):
626 e = self.make_letter_example()
627 s = e.seedir(itemlimit=(2, 2), sort=True, printout=False)
628 f = sd.fakedir_fromstring(s)
629 assert set(f.get_child_names()) == set(['a', 'b', 'e', 'f'])
630
631 def test_filter_letter_example_2_None(self):
632 e = self.make_letter_example()
633 s = e.seedir(itemlimit=(2, None), sort=True, printout=False)
634 f = sd.fakedir_fromstring(s)
635 assert set(f.get_child_names()) == set(['a', 'b', 'e', 'f', 'g', 'h'])
636
637 def test_filter_letter_example_None_0(self):
638 e = self.make_letter_example()
639 s = e.seedir(itemlimit=(None, 0), sort=True, printout=False)
640 f = sd.fakedir_fromstring(s)
641 assert set(f.get_child_names()) == set(['a', 'b', 'c', 'd'])
642
643 def test_filter_letter_example_0_0(self):
644 e = self.make_letter_example()
645 s = e.seedir(itemlimit=(0, 0), sort=True, printout=False)
646 f = sd.fakedir_fromstring(s)
647 assert len(f.get_child_names()) == 0
648
649 def test_works_with_list(self):
650 f = sd.fakedir_fromstring(large_example)
651 s = f.seedir(itemlimit=[0, None], printout=False)
652 split = s.split('\n')
653 endswithtxt = [x.endswith('txt') for x in split[1:]]
654 assert all(endswithtxt)
655
656 class TestErrorHandlingArgs:
657
658 def test_handle_errors_correct_type(self):
659 x = ErrorRaisingFDS()
660 f = sd.fakedir_fromstring(large_example)
661 s = x(f, printout=False,
662 acceptable_listdir_errors=FakedirError,
663 denied_string=' [ACCESS DENIED]')
664 assert s == large_example_access_denied
665
666 def test_handle_errors_incorrect_type(self):
667 x = ErrorRaisingFDS()
668 f = sd.fakedir_fromstring(large_example)
669 with pytest.raises(sd.errors.FakedirError):
670 _ = x(f, printout=False,
671 acceptable_listdir_errors=PermissionError,
672 denied_string=' [ACCESS DENIED]')
673
674 def test_handle_errors_None(self):
675 x = ErrorRaisingFDS()
676 f = sd.fakedir_fromstring(large_example)
677 with pytest.raises(sd.errors.FakedirError):
678 _ = x(f, printout=False,
679 acceptable_listdir_errors=None,
680 denied_string=' [ACCESS DENIED]')
681
682 def test_handle_errors_tuple(self):
683 x = ErrorRaisingFDS()
684 f = sd.fakedir_fromstring(large_example)
685 s = x(f, printout=False,
686 acceptable_listdir_errors=(FakedirError, PermissionError),
687 denied_string=' [ACCESS DENIED]')
688 assert s == large_example_access_denied
689
690 def test_handle_errors_different_string(self):
691 x = ErrorRaisingFDS()
692 f = sd.fakedir_fromstring(large_example)
693 s = x(f, printout=False,
694 acceptable_listdir_errors=FakedirError,
695 denied_string='<- BUMMER!')
696 assert s == large_example_bummer
697