Debian Codegraph @

test_autoflake.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """Test suite for autoflake."""
3
4 from __future__ import annotations
5
6 import contextlib
7 import functools
8 import io
9 import os
10 import re
11 import shutil
12 import subprocess
13 import sys
14 import tempfile
15 import unittest
16 from collections.abc import Iterator
17 from collections.abc import Mapping
18 from collections.abc import Sequence
19 from typing import Any
20
21 import autoflake
22
23 ROOT_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
24
25
26 AUTOFLAKE_COMMAND = [
27 sys.executable,
28 os.path.join(
29 ROOT_DIRECTORY,
30 "autoflake.py",
31 ),
32 ]
33
34
35 class UnitTests(unittest.TestCase):
36 """Unit tests."""
37
38 def test_imports(self) -> None:
39 self.assertGreater(len(autoflake.SAFE_IMPORTS), 0)
40
41 def test_imports_includes_builtin_modules(self) -> None:
42 """Modules compiled into the interpreter are safe to remove.
43
44 They have no file in the standard library directory, so
45 ``standard_package_names()`` cannot discover them.
46 """
47 for name in sys.builtin_module_names:
48 if name.startswith("_"):
49 continue
50 self.assertIn(name, autoflake.SAFE_IMPORTS)
51
52 def test_fix_code_removes_unused_builtin_module(self) -> None:
53 self.assertEqual(
54 "print(1)\n",
55 autoflake.fix_code("import itertools\nprint(1)\n"),
56 )
57
58 def test_unused_import_line_numbers(self) -> None:
59 self.assertEqual(
60 [1],
61 list(
62 autoflake.unused_import_line_numbers(
63 autoflake.check("import os\n"),
64 ),
65 ),
66 )
67
68 def test_unused_import_line_numbers_with_from(self) -> None:
69 self.assertEqual(
70 [1],
71 list(
72 autoflake.unused_import_line_numbers(
73 autoflake.check("from os import path\n"),
74 ),
75 ),
76 )
77
78 def test_unused_import_line_numbers_with_dot(self) -> None:
79 self.assertEqual(
80 [1],
81 list(
82 autoflake.unused_import_line_numbers(
83 autoflake.check("import os.path\n"),
84 ),
85 ),
86 )
87
88 def test_extract_package_name(self) -> None:
89 self.assertEqual("os", autoflake.extract_package_name("import os"))
90 self.assertEqual(
91 "os",
92 autoflake.extract_package_name("from os import path"),
93 )
94 self.assertEqual(
95 "os",
96 autoflake.extract_package_name("import os.path"),
97 )
98
99 def test_extract_package_name_with_incomplete_import(self) -> None:
100 self.assertIsNone(autoflake.extract_package_name("import"))
101
102 def test_extract_package_name_should_ignore_doctest_for_now(self) -> None:
103 self.assertFalse(autoflake.extract_package_name(">>> import os"))
104
105 def test_standard_package_names(self) -> None:
106 self.assertIn("os", list(autoflake.standard_package_names()))
107 self.assertIn("subprocess", list(autoflake.standard_package_names()))
108 self.assertIn("urllib", list(autoflake.standard_package_names()))
109
110 self.assertNotIn("autoflake", list(autoflake.standard_package_names()))
111 self.assertNotIn("pep8", list(autoflake.standard_package_names()))
112
113 def test_get_line_ending(self) -> None:
114 self.assertEqual("\n", autoflake.get_line_ending("\n"))
115 self.assertEqual("\n", autoflake.get_line_ending("abc\n"))
116 self.assertEqual("\t \t\n", autoflake.get_line_ending("abc\t \t\n"))
117
118 self.assertEqual("", autoflake.get_line_ending("abc"))
119 self.assertEqual("", autoflake.get_line_ending(""))
120
121 def test_get_indentation(self) -> None:
122 self.assertEqual("", autoflake.get_indentation(""))
123 self.assertEqual(" ", autoflake.get_indentation(" abc"))
124 self.assertEqual(" ", autoflake.get_indentation(" abc \n\t"))
125 self.assertEqual("\t", autoflake.get_indentation("\tabc \n\t"))
126 self.assertEqual(" \t ", autoflake.get_indentation(" \t abc \n\t"))
127 self.assertEqual("", autoflake.get_indentation(" "))
128
129 def test_filter_star_import(self) -> None:
130 self.assertEqual(
131 "from math import cos",
132 autoflake.filter_star_import(
133 "from math import *",
134 ["cos"],
135 ),
136 )
137
138 self.assertEqual(
139 "from math import cos, sin",
140 autoflake.filter_star_import(
141 "from math import *",
142 ["sin", "cos"],
143 ),
144 )
145
146 def test_filter_unused_variable(self) -> None:
147 self.assertEqual(
148 "foo()",
149 autoflake.filter_unused_variable("x = foo()"),
150 )
151
152 self.assertEqual(
153 " foo()",
154 autoflake.filter_unused_variable(" x = foo()"),
155 )
156
157 def test_filter_unused_variable_with_literal_or_name(self) -> None:
158 self.assertEqual(
159 "pass",
160 autoflake.filter_unused_variable("x = 1"),
161 )
162
163 self.assertEqual(
164 "pass",
165 autoflake.filter_unused_variable("x = y"),
166 )
167
168 self.assertEqual(
169 "pass",
170 autoflake.filter_unused_variable("x = {}"),
171 )
172
173 def test_filter_unused_variable_with_basic_data_structures(self) -> None:
174 self.assertEqual(
175 "pass",
176 autoflake.filter_unused_variable("x = dict()"),
177 )
178
179 self.assertEqual(
180 "pass",
181 autoflake.filter_unused_variable("x = list()"),
182 )
183
184 self.assertEqual(
185 "pass",
186 autoflake.filter_unused_variable("x = set()"),
187 )
188
189 def test_filter_unused_variable_should_ignore_multiline(self) -> None:
190 self.assertEqual(
191 "x = foo()\\",
192 autoflake.filter_unused_variable("x = foo()\\"),
193 )
194
195 def test_filter_unused_variable_should_multiple_assignments(self) -> None:
196 self.assertEqual(
197 "x = y = foo()",
198 autoflake.filter_unused_variable("x = y = foo()"),
199 )
200
201 def test_filter_unused_variable_with_exception(self) -> None:
202 self.assertEqual(
203 "except Exception:",
204 autoflake.filter_unused_variable("except Exception as exception:"),
205 )
206
207 self.assertEqual(
208 "except (ImportError, ValueError):",
209 autoflake.filter_unused_variable(
210 "except (ImportError, ValueError) as foo:",
211 ),
212 )
213
214 def test_filter_unused_variable_drop_rhs(self) -> None:
215 self.assertEqual(
216 "",
217 autoflake.filter_unused_variable(
218 "x = foo()",
219 drop_rhs=True,
220 ),
221 )
222
223 self.assertEqual(
224 "",
225 autoflake.filter_unused_variable(
226 " x = foo()",
227 drop_rhs=True,
228 ),
229 )
230
231 def test_filter_unused_variable_with_literal_or_name_drop_rhs(self) -> None:
232 self.assertEqual(
233 "pass",
234 autoflake.filter_unused_variable("x = 1", drop_rhs=True),
235 )
236
237 self.assertEqual(
238 "pass",
239 autoflake.filter_unused_variable("x = y", drop_rhs=True),
240 )
241
242 self.assertEqual(
243 "pass",
244 autoflake.filter_unused_variable("x = {}", drop_rhs=True),
245 )
246
247 def test_filter_unused_variable_with_basic_data_structures_drop_rhs(self) -> None:
248 self.assertEqual(
249 "pass",
250 autoflake.filter_unused_variable("x = dict()", drop_rhs=True),
251 )
252
253 self.assertEqual(
254 "pass",
255 autoflake.filter_unused_variable("x = list()", drop_rhs=True),
256 )
257
258 self.assertEqual(
259 "pass",
260 autoflake.filter_unused_variable("x = set()", drop_rhs=True),
261 )
262
263 def test_filter_unused_variable_should_ignore_multiline_drop_rhs(self) -> None:
264 self.assertEqual(
265 "x = foo()\\",
266 autoflake.filter_unused_variable("x = foo()\\", drop_rhs=True),
267 )
268
269 def test_filter_unused_variable_should_multiple_assignments_drop_rhs(self) -> None:
270 self.assertEqual(
271 "x = y = foo()",
272 autoflake.filter_unused_variable("x = y = foo()", drop_rhs=True),
273 )
274
275 def test_filter_unused_variable_with_exception_drop_rhs(self) -> None:
276 self.assertEqual(
277 "except Exception:",
278 autoflake.filter_unused_variable(
279 "except Exception as exception:",
280 drop_rhs=True,
281 ),
282 )
283
284 self.assertEqual(
285 "except (ImportError, ValueError):",
286 autoflake.filter_unused_variable(
287 "except (ImportError, ValueError) as foo:",
288 drop_rhs=True,
289 ),
290 )
291
292 def test_filter_code(self) -> None:
293 self.assertEqual(
294 """\
295 import os
296 pass
297 os.foo()
298 """,
299 "".join(
300 autoflake.filter_code(
301 """\
302 import os
303 import re
304 os.foo()
305 """,
306 ),
307 ),
308 )
309
310 def test_filter_code_with_indented_import(self) -> None:
311 self.assertEqual(
312 """\
313 import os
314 if True:
315 pass
316 os.foo()
317 """,
318 "".join(
319 autoflake.filter_code(
320 """\
321 import os
322 if True:
323 import re
324 os.foo()
325 """,
326 ),
327 ),
328 )
329
330 def test_filter_code_with_from(self) -> None:
331 self.assertEqual(
332 """\
333 pass
334 x = 1
335 """,
336 "".join(
337 autoflake.filter_code(
338 """\
339 from os import path
340 x = 1
341 """,
342 ),
343 ),
344 )
345
346 def test_filter_code_with_not_from(self) -> None:
347 self.assertEqual(
348 """\
349 pass
350 x = 1
351 """,
352 "".join(
353 autoflake.filter_code(
354 """\
355 import frommer
356 x = 1
357 """,
358 remove_all_unused_imports=True,
359 ),
360 ),
361 )
362
363 def test_filter_code_with_used_from(self) -> None:
364 self.assertEqual(
365 """\
366 import frommer
367 print(frommer)
368 """,
369 "".join(
370 autoflake.filter_code(
371 """\
372 import frommer
373 print(frommer)
374 """,
375 remove_all_unused_imports=True,
376 ),
377 ),
378 )
379
380 def test_filter_code_with_ambiguous_from(self) -> None:
381 self.assertEqual(
382 """\
383 pass
384 """,
385 "".join(
386 autoflake.filter_code(
387 """\
388 from frommer import abc, frommer, xyz
389 """,
390 remove_all_unused_imports=True,
391 ),
392 ),
393 )
394
395 def test_filter_code_should_avoid_inline_except(self) -> None:
396 line = """\
397 try: from zap import foo
398 except: from zap import bar
399 """
400 self.assertEqual(
401 line,
402 "".join(
403 autoflake.filter_code(
404 line,
405 remove_all_unused_imports=True,
406 ),
407 ),
408 )
409
410 def test_filter_code_should_avoid_escaped_newlines(self) -> None:
411 line = """\
412 try:\\
413 from zap import foo
414 except:\\
415 from zap import bar
416 """
417 self.assertEqual(
418 line,
419 "".join(
420 autoflake.filter_code(
421 line,
422 remove_all_unused_imports=True,
423 ),
424 ),
425 )
426
427 def test_filter_code_with_remove_all_unused_imports(self) -> None:
428 self.assertEqual(
429 """\
430 pass
431 pass
432 x = 1
433 """,
434 "".join(
435 autoflake.filter_code(
436 """\
437 import foo
438 import zap
439 x = 1
440 """,
441 remove_all_unused_imports=True,
442 ),
443 ),
444 )
445
446 def test_filter_code_with_additional_imports(self) -> None:
447 self.assertEqual(
448 """\
449 pass
450 import zap
451 x = 1
452 """,
453 "".join(
454 autoflake.filter_code(
455 """\
456 import foo
457 import zap
458 x = 1
459 """,
460 additional_imports=["foo", "bar"],
461 ),
462 ),
463 )
464
465 def test_filter_code_should_ignore_imports_with_inline_comment(self) -> None:
466 self.assertEqual(
467 """\
468 from os import path # foo
469 pass
470 from fake_foo import z # foo, foo, zap
471 x = 1
472 """,
473 "".join(
474 autoflake.filter_code(
475 """\
476 from os import path # foo
477 from os import path
478 from fake_foo import z # foo, foo, zap
479 x = 1
480 """,
481 ),
482 ),
483 )
484
485 def test_filter_code_should_respect_noqa(self) -> None:
486 self.assertEqual(
487 """\
488 pass
489 import re # noqa
490 from subprocess import Popen # NOQA
491 x = 1
492 """,
493 "".join(
494 autoflake.filter_code(
495 """\
496 from os import path
497 import re # noqa
498 from subprocess import Popen # NOQA
499 x = 1
500 """,
501 ),
502 ),
503 )
504
505 def test_filter_code_expand_star_imports(self) -> None:
506 self.assertEqual(
507 """\
508 from math import sin
509 sin(1)
510 """,
511 "".join(
512 autoflake.filter_code(
513 """\
514 from math import *
515 sin(1)
516 """,
517 expand_star_imports=True,
518 ),
519 ),
520 )
521
522 self.assertEqual(
523 """\
524 from math import cos, sin
525 sin(1)
526 cos(1)
527 """,
528 "".join(
529 autoflake.filter_code(
530 """\
531 from math import *
532 sin(1)
533 cos(1)
534 """,
535 expand_star_imports=True,
536 ),
537 ),
538 )
539
540 def test_filter_code_ignore_multiple_star_import(self) -> None:
541 self.assertEqual(
542 """\
543 from math import *
544 from re import *
545 sin(1)
546 cos(1)
547 """,
548 "".join(
549 autoflake.filter_code(
550 """\
551 from math import *
552 from re import *
553 sin(1)
554 cos(1)
555 """,
556 expand_star_imports=True,
557 ),
558 ),
559 )
560
561 def test_filter_code_with_special_re_symbols_in_key(self) -> None:
562 self.assertEqual(
563 """\
564 a = {
565 '????': 2,
566 }
567 print(a)
568 """,
569 "".join(
570 autoflake.filter_code(
571 """\
572 a = {
573 '????': 3,
574 '????': 2,
575 }
576 print(a)
577 """,
578 remove_duplicate_keys=True,
579 ),
580 ),
581 )
582
583 def test_multiline_import(self) -> None:
584 self.assertTrue(
585 autoflake.multiline_import(
586 r"""\
587 import os, \
588 math, subprocess
589 """,
590 ),
591 )
592
593 self.assertFalse(
594 autoflake.multiline_import(
595 """\
596 import os, math, subprocess
597 """,
598 ),
599 )
600
601 self.assertTrue(
602 autoflake.multiline_import(
603 """\
604 import os, math, subprocess
605 """,
606 previous_line="if: \\\n",
607 ),
608 )
609
610 self.assertTrue(
611 autoflake.multiline_import("from os import (path, sep)"),
612 )
613
614 def test_multiline_statement(self) -> None:
615 self.assertFalse(autoflake.multiline_statement("x = foo()"))
616
617 self.assertTrue(autoflake.multiline_statement("x = 1;"))
618 self.assertTrue(autoflake.multiline_statement("import os, \\"))
619 self.assertTrue(autoflake.multiline_statement("foo("))
620 self.assertTrue(
621 autoflake.multiline_statement(
622 "1",
623 previous_line="x = \\",
624 ),
625 )
626
627 def test_break_up_import(self) -> None:
628 self.assertEqual(
629 "import abc\nimport subprocess\nimport math\n",
630 autoflake.break_up_import("import abc, subprocess, math\n"),
631 )
632
633 def test_break_up_import_with_indentation(self) -> None:
634 self.assertEqual(
635 " import abc\n import subprocess\n import math\n",
636 autoflake.break_up_import(" import abc, subprocess, math\n"),
637 )
638
639 def test_break_up_import_should_do_nothing_on_no_line_ending(self) -> None:
640 self.assertEqual(
641 "import abc, subprocess, math",
642 autoflake.break_up_import("import abc, subprocess, math"),
643 )
644
645 def test_filter_from_import_no_remove(self) -> None:
646 self.assertEqual(
647 """\
648 from foo import abc, subprocess, math\n""",
649 autoflake.filter_from_import(
650 " from foo import abc, subprocess, math\n",
651 unused_module=[],
652 ),
653 )
654
655 def test_filter_from_import_remove_module(self) -> None:
656 self.assertEqual(
657 """\
658 from foo import subprocess, math\n""",
659 autoflake.filter_from_import(
660 " from foo import abc, subprocess, math\n",
661 unused_module=["foo.abc"],
662 ),
663 )
664
665 def test_filter_from_import_remove_all(self) -> None:
666 self.assertEqual(
667 " pass\n",
668 autoflake.filter_from_import(
669 " from foo import abc, subprocess, math\n",
670 unused_module=[
671 "foo.abc",
672 "foo.subprocess",
673 "foo.math",
674 ],
675 ),
676 )
677
678 def test_filter_code_multiline_imports(self) -> None:
679 self.assertEqual(
680 r"""\
681 import os
682 pass
683 import os
684 os.foo()
685 """,
686 "".join(
687 autoflake.filter_code(
688 r"""\
689 import os
690 import re
691 import os, \
692 math, subprocess
693 os.foo()
694 """,
695 ),
696 ),
697 )
698
699 def test_filter_code_multiline_from_imports(self) -> None:
700 self.assertEqual(
701 r"""\
702 import os
703 pass
704 from os.path import (
705 join,
706 )
707 join('a', 'b')
708 pass
709 os.foo()
710 from os.path import \
711 isdir
712 isdir('42')
713 """,
714 "".join(
715 autoflake.filter_code(
716 r"""\
717 import os
718 import re
719 from os.path import (
720 exists,
721 join,
722 )
723 join('a', 'b')
724 from os.path import \
725 abspath, basename, \
726 commonpath
727 os.foo()
728 from os.path import \
729 isfile \
730 , isdir
731 isdir('42')
732 """,
733 ),
734 ),
735 )
736
737 def test_filter_code_backslash_continuation_import_on_second_line(
738 self,
739 ) -> None:
740 """Backslash-continuation where 'import' appears on the second line.
741
742 ``from X \\<newline> import A, B`` is a valid Python multiline
743 import. autoflake used to crash with ``ValueError: not enough values
744 to unpack`` because the regex split expected ``import`` on the first
745 line. The statement must be passed through unchanged (give_up path).
746 """
747 source = "".join(
748 [
749 "from ci.zimbeast.test_scripts.framework.test_interrupt.seq_lib \\\n",
750 " import IntTestSequence, send_int\n",
751 "\n",
752 "x = send_int(1)\n",
753 ]
754 )
755 self.assertEqual(
756 source,
757 "".join(autoflake.filter_code(source, remove_all_unused_imports=True)),
758 )
759
760 def test_filter_code_should_ignore_semicolons(self) -> None:
761 self.assertEqual(
762 r"""\
763 import os
764 pass
765 import os; import math, subprocess
766 os.foo()
767 """,
768 "".join(
769 autoflake.filter_code(
770 r"""\
771 import os
772 import re
773 import os; import math, subprocess
774 os.foo()
775 """,
776 ),
777 ),
778 )
779
780 def test_filter_code_should_ignore_non_standard_library(self) -> None:
781 self.assertEqual(
782 """\
783 import os
784 import my_own_module
785 pass
786 from my_package import another_module
787 from my_package import subprocess
788 from my_blah.my_blah_blah import blah
789 os.foo()
790 """,
791 "".join(
792 autoflake.filter_code(
793 """\
794 import os
795 import my_own_module
796 import re
797 from my_package import another_module
798 from my_package import subprocess
799 from my_blah.my_blah_blah import blah
800 os.foo()
801 """,
802 ),
803 ),
804 )
805
806 def test_filter_code_should_ignore_unsafe_imports(self) -> None:
807 self.assertEqual(
808 """\
809 import rlcompleter
810 pass
811 pass
812 pass
813 print(1)
814 """,
815 "".join(
816 autoflake.filter_code(
817 """\
818 import rlcompleter
819 import sys
820 import io
821 import os
822 print(1)
823 """,
824 ),
825 ),
826 )
827
828 def test_filter_code_should_ignore_docstring(self) -> None:
829 line = """
830 def foo() -> None:
831 '''
832 >>> import math
833 '''
834 """
835 self.assertEqual(line, "".join(autoflake.filter_code(line)))
836
837 def test_with_ignore_init_module_imports_flag(self) -> None:
838 # Need a temp directory in order to specify file name as __init__.py
839 temp_directory = tempfile.mkdtemp(dir=".")
840 temp_file = os.path.join(temp_directory, "__init__.py")
841 try:
842 with open(temp_file, "w") as output:
843 output.write("import re\n")
844
845 p = subprocess.Popen(
846 list(AUTOFLAKE_COMMAND) + ["--ignore-init-module-imports", temp_file],
847 stdout=subprocess.PIPE,
848 )
849 result = p.communicate()[0].decode("utf-8")
850
851 self.assertNotIn("import re", result)
852 finally:
853 shutil.rmtree(temp_directory)
854
855 def test_without_ignore_init_module_imports_flag(self) -> None:
856 # Need a temp directory in order to specify file name as __init__.py
857 temp_directory = tempfile.mkdtemp(dir=".")
858 temp_file = os.path.join(temp_directory, "__init__.py")
859 try:
860 with open(temp_file, "w") as output:
861 output.write("import re\n")
862
863 p = subprocess.Popen(
864 list(AUTOFLAKE_COMMAND) + [temp_file],
865 stdout=subprocess.PIPE,
866 )
867 result = p.communicate()[0].decode("utf-8")
868
869 self.assertIn("import re", result)
870 finally:
871 shutil.rmtree(temp_directory)
872
873 def test_split_lines(self) -> None:
874 self.assertEqual([], autoflake._split_lines(""))
875 self.assertEqual(["x = 1\n"], autoflake._split_lines("x = 1\n"))
876 self.assertEqual(
877 ["a\r\n", "b\r", "c\n", "d"],
878 autoflake._split_lines("a\r\nb\rc\nd"),
879 )
880 # Form feeds are whitespace to the tokenizer, not line
881 # terminators; make sure they do not split lines the way
882 # str.splitlines() would.
883 self.assertEqual(["a\fb\n"], autoflake._split_lines("a\fb\n"))
884
885 def test_fix_code_with_bare_carriage_return(self) -> None:
886 """See issue #326.
887
888 A bare CR ("\\r") counts as a line terminator for the tokenizer (and
889 thus for the line numbers pyflakes reports) but not for
890 io.StringIO readlines, which used to shift every marked line
891 after it and crash in break_up_import.
892 """
893 source = """\
894
895 from t import (
896 \r a,
897 b,
898 )
899 from t import (
900 a,
901 b,
902 )
903 """
904 self.assertEqual(source, autoflake.fix_code(source))
905
906 def test_fix_code_with_bare_carriage_return_should_not_shift_lines(
907 self,
908 ) -> None:
909 """See issue #326.
910
911 The line-number shift caused by a bare "\r" must not make
912 autoflake act on the wrong lines: "os" is used and must survive,
913 while the unused "sys" import must be removed.
914 """
915 self.assertEqual(
916 """\
917 import os
918 print(os.path)
919 """,
920 "".join(
921 autoflake.fix_code(
922 """\
923 from t import (
924 \r a,
925 )
926 import sys
927 import os
928 print(os.path)
929 """,
930 remove_all_unused_imports=True,
931 ),
932 ),
933 )
934
935 def test_fix_code(self) -> None:
936 self.assertEqual(
937 """\
938 import os
939 import math
940 from sys import version
941 os.foo()
942 math.pi
943 x = version
944 """,
945 autoflake.fix_code(
946 """\
947 import os
948 import re
949 import abc, math, subprocess
950 from sys import exit, version
951 os.foo()
952 math.pi
953 x = version
954 """,
955 ),
956 )
957
958 def test_fix_code_with_from_and_as(self) -> None:
959 self.assertEqual(
960 """\
961 from collections import namedtuple as xyz
962 xyz
963 """,
964 autoflake.fix_code(
965 """\
966 from collections import defaultdict, namedtuple as xyz
967 xyz
968 """,
969 ),
970 )
971
972 self.assertEqual(
973 """\
974 from collections import namedtuple as xyz
975 xyz
976 """,
977 autoflake.fix_code(
978 """\
979 from collections import defaultdict as abc, namedtuple as xyz
980 xyz
981 """,
982 ),
983 )
984
985 self.assertEqual(
986 """\
987 from collections import namedtuple
988 namedtuple
989 """,
990 autoflake.fix_code(
991 """\
992 from collections import defaultdict as abc, namedtuple
993 namedtuple
994 """,
995 ),
996 )
997
998 self.assertEqual(
999 """\
1000 """,
1001 autoflake.fix_code(
1002 """\
1003 from collections import defaultdict as abc, namedtuple as xyz
1004 """,
1005 ),
1006 )
1007
1008 def test_fix_code_with_from_with_and_without_remove_all(self) -> None:
1009 code = """\
1010 from x import a as b, c as d
1011 """
1012
1013 self.assertEqual(
1014 """\
1015 """,
1016 autoflake.fix_code(code, remove_all_unused_imports=True),
1017 )
1018
1019 self.assertEqual(
1020 code,
1021 autoflake.fix_code(code, remove_all_unused_imports=False),
1022 )
1023
1024 def test_fix_code_with_from_and_depth_module(self) -> None:
1025 self.assertEqual(
1026 """\
1027 from distutils.version import StrictVersion
1028 StrictVersion('1.0.0')
1029 """,
1030 autoflake.fix_code(
1031 """\
1032 from distutils.version import LooseVersion, StrictVersion
1033 StrictVersion('1.0.0')
1034 """,
1035 remove_all_unused_imports=True,
1036 ),
1037 )
1038
1039 self.assertEqual(
1040 """\
1041 from distutils.version import StrictVersion as version
1042 version('1.0.0')
1043 """,
1044 autoflake.fix_code(
1045 """\
1046 from distutils.version import LooseVersion, StrictVersion as version
1047 version('1.0.0')
1048 """,
1049 remove_all_unused_imports=True,
1050 ),
1051 )
1052
1053 def test_fix_code_with_indented_from(self) -> None:
1054 self.assertEqual(
1055 """\
1056 def z() -> None:
1057 from ctypes import POINTER, byref
1058 POINTER, byref
1059 """,
1060 autoflake.fix_code(
1061 """\
1062 def z() -> None:
1063 from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
1064 POINTER, byref
1065 """,
1066 ),
1067 )
1068
1069 self.assertEqual(
1070 """\
1071 def z() -> None:
1072 pass
1073 """,
1074 autoflake.fix_code(
1075 """\
1076 def z() -> None:
1077 from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
1078 """,
1079 ),
1080 )
1081
1082 def test_fix_code_with_empty_string(self) -> None:
1083 self.assertEqual(
1084 "",
1085 autoflake.fix_code(""),
1086 )
1087
1088 def test_fix_code_with_carriage_return_in_import(self) -> None:
1089 """Should not crash on import lines corrupted by carriage returns."""
1090 autoflake.fix_code("import t\rs\nimport test\nimport0")
1091
1092 def test_fix_code_with_from_and_as_and_escaped_newline(self) -> None:
1093 """Make sure stuff after escaped newline is not lost."""
1094 result = autoflake.fix_code(
1095 """\
1096 from collections import defaultdict, namedtuple \\
1097 as xyz
1098 xyz
1099 """,
1100 )
1101 # We currently leave lines with escaped newlines as is. But in the
1102 # future this we may parse them and remove unused import accordingly.
1103 # For now, we'll work around it here.
1104 result = re.sub(r" *\\\n *as ", " as ", result)
1105
1106 self.assertEqual(
1107 """\
1108 from collections import namedtuple as xyz
1109 xyz
1110 """,
1111 autoflake.fix_code(result),
1112 )
1113
1114 def test_fix_code_with_unused_variables(self) -> None:
1115 self.assertEqual(
1116 """\
1117 def main() -> None:
1118 y = 11
1119 print(y)
1120 """,
1121 autoflake.fix_code(
1122 """\
1123 def main() -> None:
1124 x = 10
1125 y = 11
1126 print(y)
1127 """,
1128 remove_unused_variables=True,
1129 ),
1130 )
1131
1132 def test_fix_code_with_unused_variables_drop_rhs(self) -> None:
1133 self.assertEqual(
1134 """\
1135 def main() -> None:
1136 y = 11
1137 print(y)
1138 """,
1139 autoflake.fix_code(
1140 """\
1141 def main() -> None:
1142 x = 10
1143 y = 11
1144 print(y)
1145 """,
1146 remove_unused_variables=True,
1147 remove_rhs_for_unused_variables=True,
1148 ),
1149 )
1150
1151 def test_fix_code_with_unused_variables_should_skip_nonlocal(self) -> None:
1152 """pyflakes does not handle nonlocal correctly."""
1153 code = """\
1154 def bar() -> None:
1155 x = 1
1156
1157 def foo() -> None:
1158 nonlocal x
1159 x = 2
1160 """
1161 self.assertEqual(
1162 code,
1163 autoflake.fix_code(
1164 code,
1165 remove_unused_variables=True,
1166 ),
1167 )
1168
1169 def test_fix_code_with_unused_variables_should_skip_nonlocal_drop_rhs(
1170 self,
1171 ):
1172 """pyflakes does not handle nonlocal correctly."""
1173 code = """\
1174 def bar() -> None:
1175 x = 1
1176
1177 def foo() -> None:
1178 nonlocal x
1179 x = 2
1180 """
1181 self.assertEqual(
1182 code,
1183 autoflake.fix_code(
1184 code,
1185 remove_unused_variables=True,
1186 remove_rhs_for_unused_variables=True,
1187 ),
1188 )
1189
1190 def test_detect_encoding_with_bad_encoding(self) -> None:
1191 with temporary_file("# -*- coding: blah -*-\n") as filename:
1192 self.assertEqual(
1193 "latin-1",
1194 autoflake.detect_encoding(filename),
1195 )
1196
1197 def test_fix_code_with_comma_on_right(self) -> None:
1198 """pyflakes does not handle nonlocal correctly."""
1199 self.assertEqual(
1200 """\
1201 def main() -> None:
1202 pass
1203 """,
1204 autoflake.fix_code(
1205 """\
1206 def main() -> None:
1207 x = (1, 2, 3)
1208 """,
1209 remove_unused_variables=True,
1210 ),
1211 )
1212
1213 def test_fix_code_with_comma_on_right_drop_rhs(self) -> None:
1214 """pyflakes does not handle nonlocal correctly."""
1215 self.assertEqual(
1216 """\
1217 def main() -> None:
1218 pass
1219 """,
1220 autoflake.fix_code(
1221 """\
1222 def main() -> None:
1223 x = (1, 2, 3)
1224 """,
1225 remove_unused_variables=True,
1226 remove_rhs_for_unused_variables=True,
1227 ),
1228 )
1229
1230 def test_fix_code_with_unused_variables_should_skip_multiple(self) -> None:
1231 code = """\
1232 def main() -> None:
1233 (x, y, z) = (1, 2, 3)
1234 print(z)
1235 """
1236 self.assertEqual(
1237 code,
1238 autoflake.fix_code(
1239 code,
1240 remove_unused_variables=True,
1241 ),
1242 )
1243
1244 def test_fix_code_with_unused_variables_should_skip_multiple_drop_rhs(
1245 self,
1246 ):
1247 code = """\
1248 def main() -> None:
1249 (x, y, z) = (1, 2, 3)
1250 print(z)
1251 """
1252 self.assertEqual(
1253 code,
1254 autoflake.fix_code(
1255 code,
1256 remove_unused_variables=True,
1257 remove_rhs_for_unused_variables=True,
1258 ),
1259 )
1260
1261 def test_fix_code_should_handle_pyflakes_recursion_error_gracefully(self) -> None:
1262 code = "x = [{}]".format("+".join(["abc" for _ in range(2000)]))
1263 self.assertEqual(
1264 code,
1265 autoflake.fix_code(code),
1266 )
1267
1268 def test_fix_code_with_duplicate_key(self) -> None:
1269 self.assertEqual(
1270 """\
1271 a = {
1272 (0,1): 3,
1273 }
1274 print(a)
1275 """,
1276 "".join(
1277 autoflake.fix_code(
1278 """\
1279 a = {
1280 (0,1): 1,
1281 (0, 1): 'two',
1282 (0,1): 3,
1283 }
1284 print(a)
1285 """,
1286 remove_duplicate_keys=True,
1287 ),
1288 ),
1289 )
1290
1291 def test_fix_code_with_duplicate_key_longer(self) -> None:
1292 self.assertEqual(
1293 """\
1294 {
1295 'a': 0,
1296 'c': 2,
1297 'd': 3,
1298 'e': 4,
1299 'f': 5,
1300 'b': 6,
1301 }
1302 """,
1303 "".join(
1304 autoflake.fix_code(
1305 """\
1306 {
1307 'a': 0,
1308 'b': 1,
1309 'c': 2,
1310 'd': 3,
1311 'e': 4,
1312 'f': 5,
1313 'b': 6,
1314 }
1315 """,
1316 remove_duplicate_keys=True,
1317 ),
1318 ),
1319 )
1320
1321 def test_fix_code_with_duplicate_key_with_many_braces(self) -> None:
1322 self.assertEqual(
1323 """\
1324 a = None
1325
1326 {None: {None: None},
1327 }
1328
1329 {
1330 None: a.b,
1331 }
1332 """,
1333 "".join(
1334 autoflake.fix_code(
1335 """\
1336 a = None
1337
1338 {None: {None: None},
1339 }
1340
1341 {
1342 None: a.a,
1343 None: a.b,
1344 }
1345 """,
1346 remove_duplicate_keys=True,
1347 ),
1348 ),
1349 )
1350
1351 def test_fix_code_should_ignore_complex_case_of_duplicate_key(self) -> None:
1352 """We only handle simple cases."""
1353 code = """\
1354 a = {(0,1): 1, (0, 1): 'two',
1355 (0,1): 3,
1356 }
1357 print(a)
1358 """
1359
1360 self.assertEqual(
1361 code,
1362 "".join(
1363 autoflake.fix_code(
1364 code,
1365 remove_duplicate_keys=True,
1366 ),
1367 ),
1368 )
1369
1370 def test_fix_code_should_ignore_complex_case_of_duplicate_key_comma(self) -> None:
1371 """We only handle simple cases."""
1372 code = """\
1373 {
1374 1: {0,
1375 },
1376 1: {2,
1377 },
1378 }
1379 """
1380
1381 self.assertEqual(
1382 code,
1383 "".join(
1384 autoflake.fix_code(
1385 code,
1386 remove_duplicate_keys=True,
1387 ),
1388 ),
1389 )
1390
1391 def test_fix_code_should_ignore_complex_case_of_duplicate_key_partially(
1392 self,
1393 ):
1394 """We only handle simple cases."""
1395 code = """\
1396 a = {(0,1): 1, (0, 1): 'two',
1397 (0,1): 3,
1398 (2,3): 4,
1399 (2,3): 4,
1400 (2,3): 5,
1401 }
1402 print(a)
1403 """
1404
1405 self.assertEqual(
1406 """\
1407 a = {(0,1): 1, (0, 1): 'two',
1408 (0,1): 3,
1409 (2,3): 5,
1410 }
1411 print(a)
1412 """,
1413 "".join(
1414 autoflake.fix_code(
1415 code,
1416 remove_duplicate_keys=True,
1417 ),
1418 ),
1419 )
1420
1421 def test_fix_code_should_ignore_more_cases_of_duplicate_key(self) -> None:
1422 """We only handle simple cases."""
1423 code = """\
1424 a = {
1425 (0,1):
1426 1,
1427 (0, 1): 'two',
1428 (0,1): 3,
1429 }
1430 print(a)
1431 """
1432
1433 self.assertEqual(
1434 code,
1435 "".join(
1436 autoflake.fix_code(
1437 code,
1438 remove_duplicate_keys=True,
1439 ),
1440 ),
1441 )
1442
1443 def test_fix_code_should_ignore_duplicate_key_with_comments(self) -> None:
1444 """We only handle simple cases."""
1445 code = """\
1446 a = {
1447 (0,1) # : f
1448 :
1449 1,
1450 (0, 1): 'two',
1451 (0,1): 3,
1452 }
1453 print(a)
1454 """
1455
1456 self.assertEqual(
1457 code,
1458 "".join(
1459 autoflake.fix_code(
1460 code,
1461 remove_duplicate_keys=True,
1462 ),
1463 ),
1464 )
1465
1466 code = """\
1467 {
1468 1: {0,
1469 },
1470 1: #{2,
1471 #},
1472 0
1473 }
1474 """
1475
1476 self.assertEqual(
1477 code,
1478 "".join(
1479 autoflake.fix_code(
1480 code,
1481 remove_duplicate_keys=True,
1482 ),
1483 ),
1484 )
1485
1486 def test_fix_code_should_ignore_duplicate_key_with_multiline_key(self) -> None:
1487 """We only handle simple cases."""
1488 code = """\
1489 a = {
1490 (0,1
1491 ): 1,
1492 (0, 1): 'two',
1493 (0,1): 3,
1494 }
1495 print(a)
1496 """
1497
1498 self.assertEqual(
1499 code,
1500 "".join(
1501 autoflake.fix_code(
1502 code,
1503 remove_duplicate_keys=True,
1504 ),
1505 ),
1506 )
1507
1508 def test_fix_code_should_ignore_duplicate_key_with_no_comma(self) -> None:
1509 """We don't want to delete the line and leave a lone comma."""
1510 code = """\
1511 a = {
1512 (0,1) : 1
1513 ,
1514 (0, 1): 'two',
1515 (0,1): 3,
1516 }
1517 print(a)
1518 """
1519
1520 self.assertEqual(
1521 code,
1522 "".join(
1523 autoflake.fix_code(
1524 code,
1525 remove_duplicate_keys=True,
1526 ),
1527 ),
1528 )
1529
1530 def test_fix_code_keeps_pass_statements(self) -> None:
1531 code = """\
1532 if True:
1533 pass
1534 else:
1535 def foo() -> None:
1536 \"\"\" A docstring. \"\"\"
1537 pass
1538 def foo2() -> None:
1539 \"\"\" A docstring. \"\"\"
1540
1541 pass
1542 def foo3() -> None:
1543 \"\"\" A docstring. \"\"\"
1544
1545
1546 pass
1547 def bar() -> None:
1548 # abc
1549 pass
1550 def blah() -> None:
1551 123
1552 pass
1553 pass # Nope.
1554 pass
1555 """
1556
1557 self.assertEqual(
1558 code,
1559 "".join(
1560 autoflake.fix_code(
1561 code,
1562 ignore_pass_statements=True,
1563 ),
1564 ),
1565 )
1566
1567 def test_fix_code_keeps_passes_after_docstrings(self) -> None:
1568 actual = autoflake.fix_code(
1569 """\
1570 if True:
1571 pass
1572 else:
1573 def foo() -> None:
1574 \"\"\" A docstring. \"\"\"
1575 pass
1576 def foo2() -> None:
1577 \"\"\" A docstring. \"\"\"
1578
1579 pass
1580 def foo3() -> None:
1581 \"\"\" A docstring. \"\"\"
1582
1583
1584 pass
1585 def bar() -> None:
1586 # abc
1587 pass
1588 def blah() -> None:
1589 123
1590 pass
1591 pass # Nope.
1592 pass
1593 """,
1594 ignore_pass_after_docstring=True,
1595 )
1596
1597 expected = """\
1598 if True:
1599 pass
1600 else:
1601 def foo() -> None:
1602 \"\"\" A docstring. \"\"\"
1603 pass
1604 def foo2() -> None:
1605 \"\"\" A docstring. \"\"\"
1606
1607 pass
1608 def foo3() -> None:
1609 \"\"\" A docstring. \"\"\"
1610
1611
1612 pass
1613 def bar() -> None:
1614 # abc
1615 pass
1616 def blah() -> None:
1617 123
1618 pass # Nope.
1619 """
1620
1621 self.assertEqual(actual, expected)
1622
1623 def test_useless_pass_line_numbers(self) -> None:
1624 self.assertEqual(
1625 [1],
1626 list(
1627 autoflake.useless_pass_line_numbers(
1628 "pass\n",
1629 ),
1630 ),
1631 )
1632
1633 self.assertEqual(
1634 [],
1635 list(
1636 autoflake.useless_pass_line_numbers(
1637 "if True:\n pass\n",
1638 ),
1639 ),
1640 )
1641
1642 def test_useless_pass_line_numbers_with_escaped_newline(self) -> None:
1643 self.assertEqual(
1644 [],
1645 list(
1646 autoflake.useless_pass_line_numbers(
1647 "if True:\\\n pass\n",
1648 ),
1649 ),
1650 )
1651
1652 def test_useless_pass_line_numbers_with_more_complex(self) -> None:
1653 self.assertEqual(
1654 [6],
1655 list(
1656 autoflake.useless_pass_line_numbers(
1657 """\
1658 if True:
1659 pass
1660 else:
1661 True
1662 x = 1
1663 pass
1664 """,
1665 ),
1666 ),
1667 )
1668
1669 def test_useless_pass_line_numbers_after_docstring(self) -> None:
1670 actual_pass_line_numbers = list(
1671 autoflake.useless_pass_line_numbers(
1672 """\
1673 @abc.abstractmethod
1674 def some_abstract_method() -> None:
1675 \"\"\"Some docstring.\"\"\"
1676 pass
1677 """,
1678 ),
1679 )
1680
1681 expected_pass_line_numbers = [4]
1682 self.assertEqual(expected_pass_line_numbers, actual_pass_line_numbers)
1683
1684 def test_useless_pass_line_numbers_keep_pass_after_docstring(self) -> None:
1685 actual_pass_line_numbers = list(
1686 autoflake.useless_pass_line_numbers(
1687 """\
1688 @abc.abstractmethod
1689 def some_abstract_method() -> None:
1690 \"\"\"Some docstring.\"\"\"
1691 pass
1692 """,
1693 ignore_pass_after_docstring=True,
1694 ),
1695 )
1696
1697 expected_pass_line_numbers = []
1698 self.assertEqual(expected_pass_line_numbers, actual_pass_line_numbers)
1699
1700 def test_filter_useless_pass(self) -> None:
1701 self.assertEqual(
1702 """\
1703 if True:
1704 pass
1705 else:
1706 True
1707 x = 1
1708 """,
1709 "".join(
1710 autoflake.filter_useless_pass(
1711 """\
1712 if True:
1713 pass
1714 else:
1715 True
1716 x = 1
1717 pass
1718 """,
1719 ),
1720 ),
1721 )
1722
1723 def test_filter_useless_pass_with_syntax_error(self) -> None:
1724 source = """\
1725 if True:
1726 if True:
1727 if True:
1728 if True:
1729
1730 if True:
1731 pass
1732 else:
1733 True
1734 pass
1735 pass
1736 x = 1
1737 """
1738
1739 self.assertEqual(
1740 source,
1741 "".join(autoflake.filter_useless_pass(source)),
1742 )
1743
1744 def test_filter_useless_pass_more_complex(self) -> None:
1745 self.assertEqual(
1746 """\
1747 if True:
1748 pass
1749 else:
1750 def foo() -> None:
1751 pass
1752 # abc
1753 def bar() -> None:
1754 # abc
1755 pass
1756 def blah() -> None:
1757 123
1758 pass # Nope.
1759 True
1760 x = 1
1761 """,
1762 "".join(
1763 autoflake.filter_useless_pass(
1764 """\
1765 if True:
1766 pass
1767 else:
1768 def foo() -> None:
1769 pass
1770 # abc
1771 def bar() -> None:
1772 # abc
1773 pass
1774 def blah() -> None:
1775 123
1776 pass
1777 pass # Nope.
1778 pass
1779 True
1780 x = 1
1781 pass
1782 """,
1783 ),
1784 ),
1785 )
1786
1787 def test_filter_useless_pass_keep_pass_after_docstring(self) -> None:
1788 source = """\
1789 def foo() -> None:
1790 \"\"\" This is not a useless 'pass'. \"\"\"
1791 pass
1792
1793 @abc.abstractmethod
1794 def bar() -> None:
1795 \"\"\"
1796 Also this is not a useless 'pass'.
1797 \"\"\"
1798 pass
1799 """
1800 self.assertEqual(
1801 source,
1802 "".join(
1803 autoflake.filter_useless_pass(
1804 source,
1805 ignore_pass_after_docstring=True,
1806 ),
1807 ),
1808 )
1809
1810 def test_filter_useless_pass_keeps_pass_statements(self) -> None:
1811 source = """\
1812 if True:
1813 pass
1814 pass
1815 pass
1816 pass
1817 else:
1818 pass
1819 True
1820 x = 1
1821 pass
1822 """
1823
1824 self.assertEqual(
1825 source,
1826 "".join(
1827 autoflake.filter_useless_pass(
1828 source,
1829 ignore_pass_statements=True,
1830 ),
1831 ),
1832 )
1833
1834 def test_filter_useless_paspasss_with_try(self) -> None:
1835 self.assertEqual(
1836 """\
1837 import os
1838 os.foo()
1839 try:
1840 pass
1841 except ImportError:
1842 pass
1843 """,
1844 "".join(
1845 autoflake.filter_useless_pass(
1846 """\
1847 import os
1848 os.foo()
1849 try:
1850 pass
1851 pass
1852 except ImportError:
1853 pass
1854 """,
1855 ),
1856 ),
1857 )
1858
1859 def test_filter_useless_pass_leading_pass(self) -> None:
1860 self.assertEqual(
1861 """\
1862 if True:
1863 pass
1864 else:
1865 True
1866 x = 1
1867 """,
1868 "".join(
1869 autoflake.filter_useless_pass(
1870 """\
1871 if True:
1872 pass
1873 pass
1874 pass
1875 pass
1876 else:
1877 pass
1878 True
1879 x = 1
1880 pass
1881 """,
1882 ),
1883 ),
1884 )
1885
1886 def test_filter_useless_pass_leading_pass_with_number(self) -> None:
1887 self.assertEqual(
1888 """\
1889 def func11() -> None:
1890 0, 11 / 2
1891 return 1
1892 """,
1893 "".join(
1894 autoflake.filter_useless_pass(
1895 """\
1896 def func11() -> None:
1897 pass
1898 0, 11 / 2
1899 return 1
1900 """,
1901 ),
1902 ),
1903 )
1904
1905 def test_filter_useless_pass_leading_pass_with_string(self) -> None:
1906 self.assertEqual(
1907 """\
1908 def func11() -> None:
1909 'hello'
1910 return 1
1911 """,
1912 "".join(
1913 autoflake.filter_useless_pass(
1914 """\
1915 def func11() -> None:
1916 pass
1917 'hello'
1918 return 1
1919 """,
1920 ),
1921 ),
1922 )
1923
1924 def test_check(self) -> None:
1925 self.assertTrue(autoflake.check("import os"))
1926
1927 def test_check_with_bad_syntax(self) -> None:
1928 self.assertFalse(autoflake.check("foo("))
1929
1930 def test_check_with_unicode(self) -> None:
1931 self.assertFalse(autoflake.check('print("∑")'))
1932
1933 self.assertTrue(autoflake.check("import os # ∑"))
1934
1935 def test_get_diff_text(self) -> None:
1936 # We ignore the first two lines since it differs on Python 2.6.
1937 self.assertEqual(
1938 """\
1939 -foo
1940 +bar
1941 """,
1942 "\n".join(
1943 autoflake.get_diff_text(["foo\n"], ["bar\n"], "").split(
1944 "\n",
1945 )[3:],
1946 ),
1947 )
1948
1949 def test_get_diff_text_without_newline(self) -> None:
1950 # We ignore the first two lines since it differs on Python 2.6.
1951 self.assertEqual(
1952 """\
1953 -foo
1954 \\ No newline at end of file
1955 +foo
1956 """,
1957 "\n".join(
1958 autoflake.get_diff_text(["foo"], ["foo\n"], "").split(
1959 "\n",
1960 )[3:],
1961 ),
1962 )
1963
1964 def test_is_literal_or_name(self) -> None:
1965 self.assertTrue(autoflake.is_literal_or_name("123"))
1966 self.assertTrue(autoflake.is_literal_or_name("[1, 2, 3]"))
1967 self.assertTrue(autoflake.is_literal_or_name("xyz"))
1968
1969 self.assertFalse(autoflake.is_literal_or_name("xyz.prop"))
1970 self.assertFalse(autoflake.is_literal_or_name(" "))
1971
1972 def test_is_literal_or_name_with_unhashable_types(self) -> None:
1973 """Should not crash on set literals containing unhashable types."""
1974 self.assertFalse(autoflake.is_literal_or_name("{{}}"))
1975 self.assertFalse(autoflake.is_literal_or_name("{[]}"))
1976
1977 def test_is_python_file(self) -> None:
1978 self.assertTrue(
1979 autoflake.is_python_file(
1980 os.path.join(ROOT_DIRECTORY, "autoflake.py"),
1981 ),
1982 )
1983
1984 with temporary_file("#!/usr/bin/env python", suffix="") as filename:
1985 self.assertTrue(autoflake.is_python_file(filename))
1986
1987 with temporary_file("#!/usr/bin/python", suffix="") as filename:
1988 self.assertTrue(autoflake.is_python_file(filename))
1989
1990 with temporary_file("#!/usr/bin/python3", suffix="") as filename:
1991 self.assertTrue(autoflake.is_python_file(filename))
1992
1993 with temporary_file("#!/usr/bin/pythonic", suffix="") as filename:
1994 self.assertFalse(autoflake.is_python_file(filename))
1995
1996 with temporary_file("###!/usr/bin/python", suffix="") as filename:
1997 self.assertFalse(autoflake.is_python_file(filename))
1998
1999 self.assertFalse(autoflake.is_python_file(os.devnull))
2000 self.assertFalse(autoflake.is_python_file("/bin/bash"))
2001
2002 def test_is_exclude_file(self) -> None:
2003 self.assertTrue(
2004 autoflake.is_exclude_file(
2005 "1.py",
2006 ["test*", "1*"],
2007 ),
2008 )
2009
2010 self.assertFalse(
2011 autoflake.is_exclude_file(
2012 "2.py",
2013 ["test*", "1*"],
2014 ),
2015 )
2016
2017 # folder glob
2018 self.assertTrue(
2019 autoflake.is_exclude_file(
2020 "test/test.py",
2021 ["test/**.py"],
2022 ),
2023 )
2024
2025 self.assertTrue(
2026 autoflake.is_exclude_file(
2027 "test/auto_test.py",
2028 ["test/*_test.py"],
2029 ),
2030 )
2031
2032 self.assertFalse(
2033 autoflake.is_exclude_file(
2034 "test/auto_auto.py",
2035 ["test/*_test.py"],
2036 ),
2037 )
2038
2039 def test_match_file(self) -> None:
2040 with temporary_file("", suffix=".py", prefix=".") as filename:
2041 self.assertFalse(
2042 autoflake.match_file(filename, exclude=[]),
2043 msg=filename,
2044 )
2045
2046 self.assertFalse(autoflake.match_file(os.devnull, exclude=[]))
2047
2048 with temporary_file("", suffix=".py", prefix="") as filename:
2049 self.assertTrue(
2050 autoflake.match_file(filename, exclude=[]),
2051 msg=filename,
2052 )
2053
2054 def test_find_files(self) -> None:
2055 temp_directory = tempfile.mkdtemp()
2056 try:
2057 target = os.path.join(temp_directory, "dir")
2058 os.mkdir(target)
2059 with open(os.path.join(target, "a.py"), "w"):
2060 pass
2061
2062 exclude = os.path.join(target, "ex")
2063 os.mkdir(exclude)
2064 with open(os.path.join(exclude, "b.py"), "w"):
2065 pass
2066
2067 sub = os.path.join(exclude, "sub")
2068 os.mkdir(sub)
2069 with open(os.path.join(sub, "c.py"), "w"):
2070 pass
2071
2072 # FIXME: Avoid changing directory. This may interfere with parallel
2073 # test runs.
2074 cwd = os.getcwd()
2075 os.chdir(temp_directory)
2076 try:
2077 files = list(
2078 autoflake.find_files(
2079 ["dir"],
2080 True,
2081 [os.path.join("dir", "ex")],
2082 ),
2083 )
2084 finally:
2085 os.chdir(cwd)
2086
2087 file_names = [os.path.basename(f) for f in files]
2088 self.assertIn("a.py", file_names)
2089 self.assertNotIn("b.py", file_names)
2090 self.assertNotIn("c.py", file_names)
2091 finally:
2092 shutil.rmtree(temp_directory)
2093
2094 def test_exclude(self) -> None:
2095 temp_directory = tempfile.mkdtemp(dir=".")
2096 try:
2097 with open(os.path.join(temp_directory, "a.py"), "w") as output:
2098 output.write("import re\n")
2099
2100 os.mkdir(os.path.join(temp_directory, "d"))
2101 with open(
2102 os.path.join(temp_directory, "d", "b.py"),
2103 "w",
2104 ) as output:
2105 output.write("import os\n")
2106
2107 p = subprocess.Popen(
2108 list(AUTOFLAKE_COMMAND)
2109 + [temp_directory, "--recursive", "--exclude=a*"],
2110 stdout=subprocess.PIPE,
2111 )
2112 result = p.communicate()[0].decode("utf-8")
2113
2114 self.assertNotIn("import re", result)
2115 self.assertIn("import os", result)
2116 finally:
2117 shutil.rmtree(temp_directory)
2118
2119
2120 class SystemTests(unittest.TestCase):
2121 """System tests."""
2122
2123 def test_skip_file(self) -> None:
2124 skipped_file_file_text = """
2125 # autoflake: skip_file
2126 import re
2127 import os
2128 import my_own_module
2129 x = 1
2130 """
2131 with temporary_file(skipped_file_file_text) as filename:
2132 output_file = io.StringIO()
2133 autoflake._main(
2134 argv=["my_fake_program", filename, "--stdout"],
2135 standard_out=output_file,
2136 standard_error=None,
2137 )
2138 self.assertEqual(
2139 skipped_file_file_text,
2140 output_file.getvalue(),
2141 )
2142
2143 def test_skip_file_with_shebang_respect(self) -> None:
2144 skipped_file_file_text = """
2145 #!/usr/bin/env python3
2146
2147 # autoflake: skip_file
2148
2149 import re
2150 import os
2151 import my_own_module
2152 x = 1
2153 """
2154 with temporary_file(skipped_file_file_text) as filename:
2155 output_file = io.StringIO()
2156 autoflake._main(
2157 argv=["my_fake_program", filename, "--stdout"],
2158 standard_out=output_file,
2159 standard_error=None,
2160 )
2161 self.assertEqual(
2162 skipped_file_file_text,
2163 output_file.getvalue(),
2164 )
2165
2166 def test_diff(self) -> None:
2167 with temporary_file(
2168 """\
2169 import re
2170 import os
2171 import my_own_module
2172 x = 1
2173 """,
2174 ) as filename:
2175 output_file = io.StringIO()
2176 autoflake._main(
2177 argv=["my_fake_program", filename],
2178 standard_out=output_file,
2179 standard_error=None,
2180 )
2181 self.assertEqual(
2182 """\
2183 -import re
2184 -import os
2185 import my_own_module
2186 x = 1
2187 """,
2188 "\n".join(output_file.getvalue().split("\n")[3:]),
2189 )
2190
2191 def test_diff_with_nonexistent_file(self) -> None:
2192 output_file = io.StringIO()
2193 autoflake._main(
2194 argv=["my_fake_program", "nonexistent_file"],
2195 standard_out=output_file,
2196 standard_error=output_file,
2197 )
2198 self.assertIn("no such file", output_file.getvalue().lower())
2199
2200 def test_diff_with_encoding_declaration(self) -> None:
2201 with temporary_file(
2202 """\
2203 # coding: iso-8859-1
2204 import re
2205 import os
2206 import my_own_module
2207 x = 1
2208 """,
2209 ) as filename:
2210 output_file = io.StringIO()
2211 autoflake._main(
2212 argv=["my_fake_program", filename],
2213 standard_out=output_file,
2214 standard_error=None,
2215 )
2216 self.assertEqual(
2217 """\
2218 # coding: iso-8859-1
2219 -import re
2220 -import os
2221 import my_own_module
2222 x = 1
2223 """,
2224 "\n".join(output_file.getvalue().split("\n")[3:]),
2225 )
2226
2227 def test_in_place(self) -> None:
2228 with temporary_file(
2229 """\
2230 import foo
2231 x = foo
2232 import subprocess
2233 x()
2234
2235 try:
2236 import os
2237 except ImportError:
2238 import os
2239 """,
2240 ) as filename:
2241 output_file = io.StringIO()
2242 autoflake._main(
2243 argv=["my_fake_program", "--in-place", filename],
2244 standard_out=output_file,
2245 standard_error=None,
2246 )
2247 with open(filename) as f:
2248 self.assertEqual(
2249 """\
2250 import foo
2251 x = foo
2252 x()
2253
2254 try:
2255 pass
2256 except ImportError:
2257 pass
2258 """,
2259 f.read(),
2260 )
2261
2262 def test_check_with_empty_file(self) -> None:
2263 line = ""
2264
2265 with temporary_file(line) as filename:
2266 output_file = io.StringIO()
2267 autoflake._main(
2268 argv=["my_fake_program", "--check", filename],
2269 standard_out=output_file,
2270 standard_error=None,
2271 )
2272 self.assertEqual(
2273 f"{filename}: No issues detected!{os.linesep}",
2274 output_file.getvalue(),
2275 )
2276
2277 def test_check_correct_file(self) -> None:
2278 with temporary_file(
2279 """\
2280 import foo
2281 x = foo.bar
2282 print(x)
2283 """,
2284 ) as filename:
2285 output_file = io.StringIO()
2286 autoflake._main(
2287 argv=["my_fake_program", "--check", filename],
2288 standard_out=output_file,
2289 standard_error=None,
2290 )
2291 self.assertEqual(
2292 f"{filename}: No issues detected!{os.linesep}",
2293 output_file.getvalue(),
2294 )
2295
2296 def test_check_correct_file_with_quiet(self) -> None:
2297 with temporary_file(
2298 """\
2299 import foo
2300 x = foo.bar
2301 print(x)
2302 """,
2303 ) as filename:
2304 output_file = io.StringIO()
2305 autoflake._main(
2306 argv=[
2307 "my_fake_program",
2308 "--check",
2309 "--quiet",
2310 filename,
2311 ],
2312 standard_out=output_file,
2313 standard_error=None,
2314 )
2315 self.assertEqual("", output_file.getvalue())
2316
2317 def test_check_useless_pass(self) -> None:
2318 with temporary_file(
2319 """\
2320 import foo
2321 x = foo
2322 import subprocess
2323 x()
2324
2325 try:
2326 pass
2327 import os
2328 except ImportError:
2329 pass
2330 import os
2331 import sys
2332 """,
2333 ) as filename:
2334 output_file = io.StringIO()
2335 exit_status = autoflake._main(
2336 argv=["my_fake_program", "--check", filename],
2337 standard_out=output_file,
2338 standard_error=None,
2339 )
2340 self.assertEqual(exit_status, 1)
2341 self.assertEqual(
2342 f"{filename}: Unused imports/variables detected{os.linesep}",
2343 output_file.getvalue(),
2344 )
2345
2346 def test_check_with_multiple_files(self) -> None:
2347 with temporary_file("import sys") as file1:
2348 with temporary_file("import sys") as file2:
2349 output_file = io.StringIO()
2350 exit_status = autoflake._main(
2351 argv=["my_fake_program", "--check", file1, file2],
2352 standard_out=output_file,
2353 standard_error=None,
2354 )
2355 self.assertEqual(exit_status, 1)
2356 self.assertEqual(
2357 {
2358 f"{file1}: Unused imports/variables detected",
2359 f"{file2}: Unused imports/variables detected",
2360 },
2361 set(output_file.getvalue().strip().split(os.linesep)),
2362 )
2363
2364 def test_check_diff_with_empty_file(self) -> None:
2365 line = ""
2366
2367 with temporary_file(line) as filename:
2368 output_file = io.StringIO()
2369 autoflake._main(
2370 argv=["my_fake_program", "--check-diff", filename],
2371 standard_out=output_file,
2372 standard_error=None,
2373 )
2374 self.assertEqual(
2375 f"{filename}: No issues detected!{os.linesep}",
2376 output_file.getvalue(),
2377 )
2378
2379 def test_check_diff_correct_file(self) -> None:
2380 with temporary_file(
2381 """\
2382 import foo
2383 x = foo.bar
2384 print(x)
2385 """,
2386 ) as filename:
2387 output_file = io.StringIO()
2388 autoflake._main(
2389 argv=["my_fake_program", "--check-diff", filename],
2390 standard_out=output_file,
2391 standard_error=None,
2392 )
2393 self.assertEqual(
2394 f"{filename}: No issues detected!{os.linesep}",
2395 output_file.getvalue(),
2396 )
2397
2398 def test_check_diff_correct_file_with_quiet(self) -> None:
2399 with temporary_file(
2400 """\
2401 import foo
2402 x = foo.bar
2403 print(x)
2404 """,
2405 ) as filename:
2406 output_file = io.StringIO()
2407 autoflake._main(
2408 argv=[
2409 "my_fake_program",
2410 "--check-diff",
2411 "--quiet",
2412 filename,
2413 ],
2414 standard_out=output_file,
2415 standard_error=None,
2416 )
2417 self.assertEqual("", output_file.getvalue())
2418
2419 def test_check_diff_useless_pass(self) -> None:
2420 with temporary_file(
2421 """\
2422 import foo
2423 x = foo
2424 import subprocess
2425 x()
2426 try:
2427 pass
2428 import os
2429 except ImportError:
2430 pass
2431 import os
2432 import sys
2433 """,
2434 ) as filename:
2435 output_file = io.StringIO()
2436 exit_status = autoflake._main(
2437 argv=["my_fake_program", "--check-diff", filename],
2438 standard_out=output_file,
2439 standard_error=None,
2440 )
2441 self.assertEqual(exit_status, 1)
2442 self.assertEqual(
2443 """\
2444 import foo
2445 x = foo
2446 -import subprocess
2447 x()
2448 try:
2449 pass
2450 - import os
2451 except ImportError:
2452 pass
2453 - import os
2454 - import sys
2455 """,
2456 "\n".join(output_file.getvalue().split("\n")[3:]),
2457 )
2458
2459 def test_in_place_with_empty_file(self) -> None:
2460 line = ""
2461
2462 with temporary_file(line) as filename:
2463 output_file = io.StringIO()
2464 autoflake._main(
2465 argv=["my_fake_program", "--in-place", filename],
2466 standard_out=output_file,
2467 standard_error=None,
2468 )
2469 with open(filename) as f:
2470 self.assertEqual(line, f.read())
2471
2472 def test_in_place_with_with_useless_pass(self) -> None:
2473 with temporary_file(
2474 """\
2475 import foo
2476 x = foo
2477 import subprocess
2478 x()
2479
2480 try:
2481 pass
2482 import os
2483 except ImportError:
2484 pass
2485 import os
2486 import sys
2487 """,
2488 ) as filename:
2489 output_file = io.StringIO()
2490 autoflake._main(
2491 argv=["my_fake_program", "--in-place", filename],
2492 standard_out=output_file,
2493 standard_error=None,
2494 )
2495 with open(filename) as f:
2496 self.assertEqual(
2497 """\
2498 import foo
2499 x = foo
2500 x()
2501
2502 try:
2503 pass
2504 except ImportError:
2505 pass
2506 """,
2507 f.read(),
2508 )
2509
2510 def test_with_missing_file(self) -> None:
2511 output_file = io.StringIO()
2512 ignore = StubFile()
2513 autoflake._main(
2514 argv=["my_fake_program", "--in-place", ".fake"],
2515 standard_out=output_file,
2516 standard_error=ignore, # type: ignore
2517 )
2518 self.assertFalse(output_file.getvalue())
2519
2520 def test_ignore_hidden_directories(self) -> None:
2521 with temporary_directory() as directory:
2522 with temporary_directory(
2523 prefix=".",
2524 directory=directory,
2525 ) as inner_directory:
2526 with temporary_file(
2527 """\
2528 import re
2529 import os
2530 """,
2531 directory=inner_directory,
2532 ):
2533 output_file = io.StringIO()
2534 autoflake._main(
2535 argv=[
2536 "my_fake_program",
2537 "--recursive",
2538 directory,
2539 ],
2540 standard_out=output_file,
2541 standard_error=None,
2542 )
2543 self.assertEqual(
2544 "",
2545 output_file.getvalue().strip(),
2546 )
2547
2548 def test_in_place_and_stdout(self) -> None:
2549 output_file = io.StringIO()
2550 self.assertRaises(
2551 SystemExit,
2552 autoflake._main,
2553 argv=["my_fake_program", "--in-place", "--stdout", __file__],
2554 standard_out=output_file,
2555 standard_error=output_file,
2556 )
2557
2558 def test_end_to_end(self) -> None:
2559 with temporary_file(
2560 """\
2561 import fake_fake, fake_foo, fake_bar, fake_zoo
2562 import re, os
2563 x = os.sep
2564 print(x)
2565 """,
2566 ) as filename:
2567 process = subprocess.Popen(
2568 AUTOFLAKE_COMMAND
2569 + [
2570 "--imports=fake_foo,fake_bar",
2571 filename,
2572 ],
2573 stdout=subprocess.PIPE,
2574 )
2575 self.assertEqual(
2576 """\
2577 -import fake_fake, fake_foo, fake_bar, fake_zoo
2578 -import re, os
2579 +import fake_fake
2580 +import fake_zoo
2581 +import os
2582 x = os.sep
2583 print(x)
2584 """,
2585 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2586 )
2587
2588 def test_end_to_end_multiple_files(self) -> None:
2589 with temporary_file(
2590 """\
2591 import fake_fake, fake_foo, fake_bar, fake_zoo
2592 import re, os
2593 x = os.sep
2594 print(x)
2595 """,
2596 ) as filename1:
2597 with temporary_file(
2598 """\
2599 import os
2600 x = os.sep
2601 print(x)
2602 """,
2603 ) as filename2:
2604 process = subprocess.Popen(
2605 AUTOFLAKE_COMMAND
2606 + [
2607 "--imports=fake_foo,fake_bar",
2608 "--check",
2609 "--jobs=2",
2610 filename1,
2611 filename2,
2612 ],
2613 stdout=subprocess.PIPE,
2614 )
2615
2616 status_code = process.wait()
2617 self.assertEqual(1, status_code)
2618
2619 def test_end_to_end_with_remove_all_unused_imports(self) -> None:
2620 with temporary_file(
2621 """\
2622 import fake_fake, fake_foo, fake_bar, fake_zoo
2623 import re, os
2624 x = os.sep
2625 print(x)
2626 """,
2627 ) as filename:
2628 process = subprocess.Popen(
2629 AUTOFLAKE_COMMAND
2630 + [
2631 "--remove-all",
2632 filename,
2633 ],
2634 stdout=subprocess.PIPE,
2635 )
2636 self.assertEqual(
2637 """\
2638 -import fake_fake, fake_foo, fake_bar, fake_zoo
2639 -import re, os
2640 +import os
2641 x = os.sep
2642 print(x)
2643 """,
2644 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2645 )
2646
2647 def test_end_to_end_with_remove_duplicate_keys_multiple_lines(self) -> None:
2648 with temporary_file(
2649 """\
2650 a = {
2651 'b': 456,
2652 'a': 123,
2653 'b': 7834,
2654 'a': 'wow',
2655 'b': 456,
2656 'c': 'hello',
2657 'c': 'hello2',
2658 'b': 'hiya',
2659 }
2660 print(a)
2661 """,
2662 ) as filename:
2663 process = subprocess.Popen(
2664 AUTOFLAKE_COMMAND
2665 + [
2666 "--remove-duplicate-keys",
2667 filename,
2668 ],
2669 stdout=subprocess.PIPE,
2670 )
2671 self.assertEqual(
2672 """\
2673 a = {
2674 - 'b': 456,
2675 - 'a': 123,
2676 - 'b': 7834,
2677 'a': 'wow',
2678 - 'b': 456,
2679 - 'c': 'hello',
2680 'c': 'hello2',
2681 'b': 'hiya',
2682 }
2683 """,
2684 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2685 )
2686
2687 def test_end_to_end_with_remove_duplicate_keys_and_other_errors(self) -> None:
2688 with temporary_file(
2689 """\
2690 from math import *
2691 print(sin(4))
2692 a = { # Hello
2693 'b': 456,
2694 'a': 123,
2695 'b': 7834,
2696 'a': 'wow',
2697 'b': 456,
2698 'c': 'hello',
2699 'c': 'hello2',
2700 'b': 'hiya',
2701 }
2702 print(a)
2703 """,
2704 ) as filename:
2705 process = subprocess.Popen(
2706 AUTOFLAKE_COMMAND
2707 + [
2708 "--remove-duplicate-keys",
2709 filename,
2710 ],
2711 stdout=subprocess.PIPE,
2712 )
2713 self.assertEqual(
2714 """\
2715 from math import *
2716 print(sin(4))
2717 a = { # Hello
2718 - 'b': 456,
2719 - 'a': 123,
2720 - 'b': 7834,
2721 'a': 'wow',
2722 - 'b': 456,
2723 - 'c': 'hello',
2724 'c': 'hello2',
2725 'b': 'hiya',
2726 }
2727 """,
2728 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2729 )
2730
2731 def test_end_to_end_with_remove_duplicate_keys_tuple(self) -> None:
2732 with temporary_file(
2733 """\
2734 a = {
2735 (0,1): 1,
2736 (0, 1): 'two',
2737 (0,1): 3,
2738 }
2739 print(a)
2740 """,
2741 ) as filename:
2742 process = subprocess.Popen(
2743 AUTOFLAKE_COMMAND
2744 + [
2745 "--remove-duplicate-keys",
2746 filename,
2747 ],
2748 stdout=subprocess.PIPE,
2749 )
2750 self.assertEqual(
2751 """\
2752 a = {
2753 - (0,1): 1,
2754 - (0, 1): 'two',
2755 (0,1): 3,
2756 }
2757 print(a)
2758 """,
2759 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2760 )
2761
2762 def test_end_to_end_with_error(self) -> None:
2763 with temporary_file(
2764 """\
2765 import fake_fake, fake_foo, fake_bar, fake_zoo
2766 import re, os
2767 x = os.sep
2768 print(x)
2769 """,
2770 ) as filename:
2771 process = subprocess.Popen(
2772 AUTOFLAKE_COMMAND
2773 + [
2774 "--imports=fake_foo,fake_bar",
2775 "--remove-all",
2776 filename,
2777 ],
2778 stderr=subprocess.PIPE,
2779 )
2780 self.assertIn(
2781 "not allowed with argument",
2782 process.communicate()[1].decode(),
2783 )
2784
2785 def test_end_to_end_from_stdin(self) -> None:
2786 stdin_data = b"""\
2787 import fake_fake, fake_foo, fake_bar, fake_zoo
2788 import re, os
2789 x = os.sep
2790 print(x)
2791 """
2792 process = subprocess.Popen(
2793 AUTOFLAKE_COMMAND + ["--remove-all", "-"],
2794 stdout=subprocess.PIPE,
2795 stdin=subprocess.PIPE,
2796 )
2797 stdout, _ = process.communicate(stdin_data)
2798 self.assertEqual(
2799 """\
2800 import os
2801 x = os.sep
2802 print(x)
2803 """,
2804 "\n".join(stdout.decode().split(os.linesep)),
2805 )
2806
2807 def test_end_to_end_from_stdin_with_in_place(self) -> None:
2808 stdin_data = b"""\
2809 import fake_fake, fake_foo, fake_bar, fake_zoo
2810 import re, os, sys
2811 x = os.sep
2812 print(x)
2813 """
2814 process = subprocess.Popen(
2815 AUTOFLAKE_COMMAND + ["--remove-all", "--in-place", "-"],
2816 stdout=subprocess.PIPE,
2817 stdin=subprocess.PIPE,
2818 )
2819 stdout, _ = process.communicate(stdin_data)
2820 self.assertEqual(
2821 """\
2822 import os
2823 x = os.sep
2824 print(x)
2825 """,
2826 "\n".join(stdout.decode().split(os.linesep)),
2827 )
2828
2829 def test_end_to_end_dont_remove_unused_imports_when_not_using_flag(self) -> None:
2830 with temporary_file(
2831 """\
2832 from . import fake_bar
2833 from . import fake_foo
2834 fake_foo.fake_function()
2835 """,
2836 ) as filename:
2837 process = subprocess.Popen(
2838 AUTOFLAKE_COMMAND
2839 + [
2840 filename,
2841 ],
2842 stdout=subprocess.PIPE,
2843 )
2844 self.assertEqual(
2845 "",
2846 "\n".join(process.communicate()[0].decode().split(os.linesep)[3:]),
2847 )
2848
2849
2850 class MultilineFromImportTests(unittest.TestCase):
2851 def test_is_over(self) -> None:
2852 filt = autoflake.FilterMultilineImport("from . import (\n")
2853 self.assertTrue(filt.is_over("module)\n"))
2854 self.assertTrue(filt.is_over(" )\n"))
2855 self.assertTrue(filt.is_over(" ) # comment\n"))
2856 self.assertTrue(filt.is_over("from module import (a, b)\n"))
2857 self.assertFalse(filt.is_over("# )"))
2858 self.assertFalse(filt.is_over("module\n"))
2859 self.assertFalse(filt.is_over("module, \\\n"))
2860 self.assertFalse(filt.is_over("\n"))
2861
2862 filt = autoflake.FilterMultilineImport("from . import module, \\\n")
2863 self.assertTrue(filt.is_over("module\n"))
2864 self.assertTrue(filt.is_over("\n"))
2865 self.assertTrue(filt.is_over("m1, m2 # comment with \\\n"))
2866 self.assertFalse(filt.is_over("m1, m2 \\\n"))
2867 self.assertFalse(filt.is_over("m1, m2 \\ #\n"))
2868 self.assertFalse(filt.is_over("m1, m2 \\ # comment with \\\n"))
2869 self.assertFalse(filt.is_over("\\\n"))
2870
2871 # "Multiline" imports that are not really multiline
2872 filt = autoflake.FilterMultilineImport(
2873 "import os; import math, subprocess",
2874 )
2875 self.assertTrue(filt.is_over())
2876
2877 unused = ()
2878
2879 def assert_fix(
2880 self,
2881 lines: Sequence[str],
2882 result: str,
2883 remove_all: bool = True,
2884 ) -> None:
2885 fixer = autoflake.FilterMultilineImport(
2886 lines[0],
2887 remove_all_unused_imports=remove_all,
2888 unused_module=self.unused,
2889 )
2890 fixed = functools.reduce(
2891 lambda acc, x: acc(x) if isinstance(acc, autoflake.PendingFix) else acc,
2892 lines[1:],
2893 fixer(),
2894 )
2895 self.assertEqual(fixed, result)
2896
2897 def test_fix(self) -> None:
2898 self.unused = ["third_party.lib" + str(x) for x in (1, 3, 4)]
2899
2900 # Example m0 (isort)
2901 self.assert_fix(
2902 [
2903 "from third_party import (lib1, lib2, lib3,\n",
2904 " lib4, lib5, lib6)\n",
2905 ],
2906 "from third_party import (lib2, lib5, lib6)\n",
2907 )
2908
2909 # Example m1(isort)
2910 self.assert_fix(
2911 [
2912 "from third_party import (lib1,\n",
2913 " lib2,\n",
2914 " lib3,\n",
2915 " lib4,\n",
2916 " lib5,\n",
2917 " lib6)\n",
2918 ],
2919 "from third_party import (lib2,\n"
2920 " lib5,\n"
2921 " lib6)\n",
2922 )
2923
2924 # Variation m1(isort)
2925 self.assert_fix(
2926 [
2927 "from third_party import (lib1\n",
2928 " ,lib2\n",
2929 " ,lib3\n",
2930 " ,lib4\n",
2931 " ,lib5\n",
2932 " ,lib6)\n",
2933 ],
2934 "from third_party import (lib2\n"
2935 " ,lib5\n"
2936 " ,lib6)\n",
2937 )
2938
2939 # Example m2 (isort)
2940 self.assert_fix(
2941 [
2942 "from third_party import \\\n",
2943 " lib1, lib2, lib3, \\\n",
2944 " lib4, lib5, lib6\n",
2945 ],
2946 "from third_party import \\\n lib2, lib5, lib6\n",
2947 )
2948
2949 # Example m3 (isort)
2950 self.assert_fix(
2951 [
2952 "from third_party import (\n",
2953 " lib1,\n",
2954 " lib2,\n",
2955 " lib3,\n",
2956 " lib4,\n",
2957 " lib5\n",
2958 ")\n",
2959 ],
2960 "from third_party import (\n lib2,\n lib5\n)\n",
2961 )
2962
2963 # Example m4 (isort)
2964 self.assert_fix(
2965 [
2966 "from third_party import (\n",
2967 " lib1, lib2, lib3, lib4,\n",
2968 " lib5, lib6)\n",
2969 ],
2970 "from third_party import (\n lib2, lib5, lib6)\n",
2971 )
2972
2973 # Example m5 (isort)
2974 self.assert_fix(
2975 [
2976 "from third_party import (\n",
2977 " lib1, lib2, lib3, lib4,\n",
2978 " lib5, lib6\n",
2979 ")\n",
2980 ],
2981 "from third_party import (\n lib2, lib5, lib6\n)\n",
2982 )
2983
2984 # Some Deviations
2985 self.assert_fix(
2986 [
2987 "from third_party import (\n",
2988 " lib1\\\n", # only unused + line continuation
2989 " ,lib2, \n",
2990 " libA\n", # used import with no commas
2991 " ,lib3, \n", # leading and trailing commas + unused import
2992 " libB, \n",
2993 " \\\n", # empty line with continuation
2994 " lib4,\n", # unused import with comment
2995 ")\n",
2996 ],
2997 "from third_party import (\n lib2\\\n ,libA, \n libB,\n)\n",
2998 )
2999
3000 self.assert_fix(
3001 [
3002 "from third_party import (\n",
3003 " lib1\n",
3004 ",\n",
3005 " lib2\n",
3006 ",\n",
3007 " lib3\n",
3008 ",\n",
3009 " lib4\n",
3010 ",\n",
3011 " lib5\n",
3012 ")\n",
3013 ],
3014 "from third_party import (\n lib2\n,\n lib5\n)\n",
3015 )
3016
3017 self.assert_fix(
3018 [
3019 "from third_party import (\n",
3020 " lib1 \\\n",
3021 ", \\\n",
3022 " lib2 \\\n",
3023 ",\\\n",
3024 " lib3\n",
3025 ",\n",
3026 " lib4\n",
3027 ",\n",
3028 " lib5 \\\n",
3029 ")\n",
3030 ],
3031 "from third_party import (\n lib2 \\\n, \\\n lib5 \\\n)\n",
3032 )
3033
3034 def test_indentation(self) -> None:
3035 # Some weird indentation examples
3036 self.unused = ["third_party.lib" + str(x) for x in (1, 3, 4)]
3037 self.assert_fix(
3038 [
3039 " from third_party import (\n",
3040 " lib1, lib2, lib3, lib4,\n",
3041 " lib5, lib6\n",
3042 ")\n",
3043 ],
3044 " from third_party import (\n lib2, lib5, lib6\n)\n",
3045 )
3046 self.assert_fix(
3047 [
3048 "\tfrom third_party import \\\n",
3049 "\t\tlib1, lib2, lib3, \\\n",
3050 "\t\tlib4, lib5, lib6\n",
3051 ],
3052 "\tfrom third_party import \\\n\t\tlib2, lib5, lib6\n",
3053 )
3054
3055 def test_fix_relative(self) -> None:
3056 # Example m0 (isort)
3057 self.unused = [".lib" + str(x) for x in (1, 3, 4)]
3058 self.assert_fix(
3059 [
3060 "from . import (lib1, lib2, lib3,\n",
3061 " lib4, lib5, lib6)\n",
3062 ],
3063 "from . import (lib2, lib5, lib6)\n",
3064 )
3065
3066 # Example m1(isort)
3067 self.unused = ["..lib" + str(x) for x in (1, 3, 4)]
3068 self.assert_fix(
3069 [
3070 "from .. import (lib1,\n",
3071 " lib2,\n",
3072 " lib3,\n",
3073 " lib4,\n",
3074 " lib5,\n",
3075 " lib6)\n",
3076 ],
3077 "from .. import (lib2,\n lib5,\n lib6)\n",
3078 )
3079
3080 # Example m2 (isort)
3081 self.unused = ["...lib" + str(x) for x in (1, 3, 4)]
3082 self.assert_fix(
3083 [
3084 "from ... import \\\n",
3085 " lib1, lib2, lib3, \\\n",
3086 " lib4, lib5, lib6\n",
3087 ],
3088 "from ... import \\\n lib2, lib5, lib6\n",
3089 )
3090
3091 # Example m3 (isort)
3092 self.unused = [".parent.lib" + str(x) for x in (1, 3, 4)]
3093 self.assert_fix(
3094 [
3095 "from .parent import (\n",
3096 " lib1,\n",
3097 " lib2,\n",
3098 " lib3,\n",
3099 " lib4,\n",
3100 " lib5\n",
3101 ")\n",
3102 ],
3103 "from .parent import (\n lib2,\n lib5\n)\n",
3104 )
3105
3106 def test_fix_without_from(self) -> None:
3107 self.unused = ["lib" + str(x) for x in (1, 3, 4)]
3108
3109 # Multiline but not "from"
3110 self.assert_fix(
3111 [
3112 "import \\\n",
3113 " lib1, lib2, lib3 \\\n",
3114 " ,lib4, lib5, lib6\n",
3115 ],
3116 "import \\\n lib2, lib5, lib6\n",
3117 )
3118 self.assert_fix(
3119 [
3120 "import lib1, lib2, lib3, \\\n",
3121 " lib4, lib5, lib6\n",
3122 ],
3123 "import lib2, lib5, lib6\n",
3124 )
3125
3126 # Problematic example without "from"
3127 self.assert_fix(
3128 [
3129 "import \\\n",
3130 " lib1,\\\n",
3131 " lib2, \\\n",
3132 " libA\\\n", # used import with no commas
3133 " ,lib3, \\\n", # leading and trailing commas with unused
3134 " libB, \\\n",
3135 " \\ \n", # empty line with continuation
3136 " lib4\\\n", # unused import with comment
3137 "\n",
3138 ],
3139 "import \\\n lib2,\\\n libA, \\\n libB\\\n\n",
3140 )
3141
3142 self.unused = [f"lib{x}.x.y.z" for x in (1, 3, 4)]
3143 self.assert_fix(
3144 [
3145 "import \\\n",
3146 " lib1.x.y.z \\",
3147 " , \\\n",
3148 " lib2.x.y.z \\\n",
3149 " , \\\n",
3150 " lib3.x.y.z \\\n",
3151 " , \\\n",
3152 " lib4.x.y.z \\\n",
3153 " , \\\n",
3154 " lib5.x.y.z\n",
3155 ],
3156 "import \\\n lib2.x.y.z \\ , \\\n lib5.x.y.z\n",
3157 )
3158
3159 def test_give_up(self) -> None:
3160 # Semicolon
3161 self.unused = ["lib" + str(x) for x in (1, 3, 4)]
3162 self.assert_fix(
3163 [
3164 "import \\\n",
3165 " lib1, lib2, lib3, \\\n",
3166 " lib4, lib5; import lib6\n",
3167 ],
3168 "import \\\n lib1, lib2, lib3, \\\n lib4, lib5; import lib6\n",
3169 )
3170 # Comments
3171 self.unused = [".lib" + str(x) for x in (1, 3, 4)]
3172 self.assert_fix(
3173 [
3174 "from . import ( # comment\n",
3175 " lib1,\\\n", # only unused + line continuation
3176 " lib2, \n",
3177 " libA\n", # used import with no commas
3178 " ,lib3, \n", # leading and trailing commas + unused import
3179 " libB, \n",
3180 " \\ \n", # empty line with continuation
3181 " lib4, # noqa \n", # unused import with comment
3182 ") ; import sys\n",
3183 ],
3184 "from . import ( # comment\n"
3185 " lib1,\\\n"
3186 " lib2, \n"
3187 " libA\n"
3188 " ,lib3, \n"
3189 " libB, \n"
3190 " \\ \n"
3191 " lib4, # noqa \n"
3192 ") ; import sys\n",
3193 )
3194
3195 def test_just_one_import_used(self) -> None:
3196 self.unused = ["lib2"]
3197 self.assert_fix(
3198 [
3199 "import \\\n",
3200 " lib1\n",
3201 ],
3202 "import \\\n lib1\n",
3203 )
3204 self.assert_fix(
3205 [
3206 "import \\\n",
3207 " lib2\n",
3208 ],
3209 "pass\n",
3210 )
3211 # Example from issue #8
3212 self.unused = ["re.subn"]
3213 self.assert_fix(
3214 [
3215 "\tfrom re import (subn)\n",
3216 ],
3217 "\tpass\n",
3218 )
3219
3220 def test_just_one_import_left(self) -> None:
3221 # Examples from issue #8
3222 self.unused = ["math.sqrt"]
3223 self.assert_fix(
3224 [
3225 "from math import (\n",
3226 " sqrt,\n",
3227 " log\n",
3228 " )\n",
3229 ],
3230 "from math import (\n log\n )\n",
3231 )
3232 self.unused = ["module.b"]
3233 self.assert_fix(
3234 [
3235 "from module import (a, b)\n",
3236 ],
3237 "from module import a\n",
3238 )
3239 self.assert_fix(
3240 [
3241 "from module import (a,\n",
3242 " b)\n",
3243 ],
3244 "from module import a\n",
3245 )
3246 self.unused = []
3247 self.assert_fix(
3248 [
3249 "from re import (subn)\n",
3250 ],
3251 "from re import (subn)\n",
3252 )
3253
3254 def test_no_empty_imports(self) -> None:
3255 self.unused = ["lib" + str(x) for x in (1, 3, 4)]
3256 self.assert_fix(
3257 [
3258 "import \\\n",
3259 " lib1, lib3, \\\n",
3260 " lib4 \n",
3261 ],
3262 "pass \n",
3263 )
3264
3265 # Indented parenthesized block
3266 self.unused = [".parent.lib" + str(x) for x in (1, 3, 4)]
3267 self.assert_fix(
3268 [
3269 "\t\tfrom .parent import (\n",
3270 " lib1,\n",
3271 " lib3,\n",
3272 " lib4,\n",
3273 ")\n",
3274 ],
3275 "\t\tpass\n",
3276 )
3277
3278 def test_without_remove_all(self) -> None:
3279 self.unused = ["lib" + str(x) for x in (1, 3, 4)]
3280 self.assert_fix(
3281 [
3282 "import \\\n",
3283 " lib1,\\\n",
3284 " lib3,\\\n",
3285 " lib4\n",
3286 ],
3287 "import \\\n lib1,\\\n lib3,\\\n lib4\n",
3288 remove_all=False,
3289 )
3290
3291 self.unused += ["os.path." + x for x in ("dirname", "isdir", "join")]
3292 self.assert_fix(
3293 [
3294 "from os.path import (\n",
3295 " dirname,\n",
3296 " isdir,\n",
3297 " join,\n",
3298 ")\n",
3299 ],
3300 "pass\n",
3301 remove_all=False,
3302 )
3303 self.assert_fix(
3304 [
3305 "import \\\n",
3306 " os.path.dirname, \\\n",
3307 " lib1, \\\n",
3308 " lib3\n",
3309 ],
3310 "import \\\n lib1, \\\n lib3\n",
3311 remove_all=False,
3312 )
3313
3314
3315 class ConfigFileTest(unittest.TestCase):
3316 def setUp(self) -> None:
3317 self.tmpdir = tempfile.mkdtemp(prefix="autoflake.")
3318
3319 def tearDown(self) -> None:
3320 if self.tmpdir:
3321 shutil.rmtree(self.tmpdir)
3322
3323 def effective_path(self, path: str, is_file: bool = True) -> str:
3324 path = os.path.normpath(path)
3325 if os.path.isabs(path):
3326 raise ValueError("Should not create an absolute test path")
3327 effective_path = os.path.sep.join([self.tmpdir, path])
3328 if not effective_path.startswith(
3329 f"{self.tmpdir}{os.path.sep}",
3330 ) and (effective_path != self.tmpdir or is_file):
3331 raise ValueError("Should create a path within the tmp dir only")
3332 return effective_path
3333
3334 def create_dir(self, path) -> None:
3335 effective_path = self.effective_path(path, False)
3336 os.makedirs(effective_path, exist_ok=True)
3337
3338 def create_file(self, path, contents="") -> None:
3339 effective_path = self.effective_path(path)
3340 self.create_dir(os.path.split(path)[0])
3341 with open(effective_path, "w") as f:
3342 f.write(contents)
3343
3344 def with_defaults(self, **kwargs: Any) -> Mapping[str, Any]:
3345 return {
3346 "check": False,
3347 "check_diff": False,
3348 "expand_star_imports": False,
3349 "ignore_init_module_imports": False,
3350 "ignore_pass_after_docstring": False,
3351 "ignore_pass_statements": False,
3352 "in_place": False,
3353 "quiet": False,
3354 "recursive": False,
3355 "remove_all_unused_imports": False,
3356 "remove_duplicate_keys": False,
3357 "remove_rhs_for_unused_variables": False,
3358 "remove_unused_variables": False,
3359 "write_to_stdout": False,
3360 **kwargs,
3361 }
3362
3363 def test_no_config_file(self) -> None:
3364 self.create_file("test_me.py")
3365 original_args = {
3366 "files": [self.effective_path("test_me.py")],
3367 }
3368 args, success = autoflake.merge_configuration_file(original_args)
3369 assert success is True
3370 assert args == self.with_defaults(**original_args)
3371
3372 def test_non_nested_pyproject_toml_empty(self) -> None:
3373 self.create_file("test_me.py")
3374 self.create_file("pyproject.toml", '[tool.other]\nprop="value"\n')
3375 files = [self.effective_path("test_me.py")]
3376 original_args = {"files": files}
3377 args, success = autoflake.merge_configuration_file(original_args)
3378 assert success is True
3379 assert args == self.with_defaults(**original_args)
3380
3381 def test_non_nested_pyproject_toml_non_empty(self) -> None:
3382 self.create_file("test_me.py")
3383 self.create_file(
3384 "pyproject.toml",
3385 "[tool.autoflake]\nexpand-star-imports=true\n",
3386 )
3387 files = [self.effective_path("test_me.py")]
3388 args, success = autoflake.merge_configuration_file({"files": files})
3389 assert success is True
3390 assert args == self.with_defaults(
3391 files=files,
3392 expand_star_imports=True,
3393 )
3394
3395 def test_non_nested_setup_cfg_non_empty(self) -> None:
3396 self.create_file("test_me.py")
3397 self.create_file(
3398 "setup.cfg",
3399 "[other]\nexpand-star-imports = yes\n",
3400 )
3401 files = [self.effective_path("test_me.py")]
3402 args, success = autoflake.merge_configuration_file({"files": files})
3403 assert success is True
3404 assert args == self.with_defaults(files=files)
3405
3406 def test_non_nested_setup_cfg_empty(self) -> None:
3407 self.create_file("test_me.py")
3408 self.create_file(
3409 "setup.cfg",
3410 "[autoflake]\nexpand-star-imports = yes\n",
3411 )
3412 files = [self.effective_path("test_me.py")]
3413 args, success = autoflake.merge_configuration_file({"files": files})
3414 assert success is True
3415 assert args == self.with_defaults(
3416 files=files,
3417 expand_star_imports=True,
3418 )
3419
3420 def test_nested_file(self) -> None:
3421 self.create_file("nested/file/test_me.py")
3422 self.create_file(
3423 "pyproject.toml",
3424 "[tool.autoflake]\nexpand-star-imports=true\n",
3425 )
3426 files = [self.effective_path("nested/file/test_me.py")]
3427 args, success = autoflake.merge_configuration_file({"files": files})
3428 assert success is True
3429 assert args == self.with_defaults(
3430 files=files,
3431 expand_star_imports=True,
3432 )
3433
3434 def test_common_path_nested_file_do_not_load(self) -> None:
3435 self.create_file("nested/file/test_me.py")
3436 self.create_file("nested/other/test_me.py")
3437 self.create_file(
3438 "nested/file/pyproject.toml",
3439 "[tool.autoflake]\nexpand-star-imports=true\n",
3440 )
3441 files = [
3442 self.effective_path("nested/file/test_me.py"),
3443 self.effective_path("nested/other/test_me.py"),
3444 ]
3445 args, success = autoflake.merge_configuration_file({"files": files})
3446 assert success is True
3447 assert args == self.with_defaults(files=files)
3448
3449 def test_common_path_nested_file_do_load(self) -> None:
3450 self.create_file("nested/file/test_me.py")
3451 self.create_file("nested/other/test_me.py")
3452 self.create_file(
3453 "nested/pyproject.toml",
3454 "[tool.autoflake]\nexpand-star-imports=true\n",
3455 )
3456 files = [
3457 self.effective_path("nested/file/test_me.py"),
3458 self.effective_path("nested/other/test_me.py"),
3459 ]
3460 args, success = autoflake.merge_configuration_file({"files": files})
3461 assert success is True
3462 assert args == self.with_defaults(
3463 files=files,
3464 expand_star_imports=True,
3465 )
3466
3467 def test_common_path_instead_of_common_prefix(self) -> None:
3468 """Using common prefix would result in a failure."""
3469 self.create_file("nested/file-foo/test_me.py")
3470 self.create_file("nested/file-bar/test_me.py")
3471 self.create_file(
3472 "nested/file/pyproject.toml",
3473 "[tool.autoflake]\nexpand-star-imports=true\n",
3474 )
3475 files = [
3476 self.effective_path("nested/file-foo/test_me.py"),
3477 self.effective_path("nested/file-bar/test_me.py"),
3478 ]
3479 args, success = autoflake.merge_configuration_file({"files": files})
3480 assert success is True
3481 assert args == self.with_defaults(files=files)
3482
3483 def test_continue_search_if_no_config_found(self) -> None:
3484 self.create_file("nested/test_me.py")
3485 self.create_file(
3486 "nested/pyproject.toml",
3487 '[tool.other]\nprop = "value"\n',
3488 )
3489 self.create_file(
3490 "pyproject.toml",
3491 "[tool.autoflake]\nexpand-star-imports = true\n",
3492 )
3493 files = [self.effective_path("nested/test_me.py")]
3494 args, success = autoflake.merge_configuration_file({"files": files})
3495 assert success is True
3496 assert args == self.with_defaults(
3497 files=files,
3498 expand_star_imports=True,
3499 )
3500
3501 def test_stop_search_if_config_found(self) -> None:
3502 self.create_file("nested/test_me.py")
3503 self.create_file(
3504 "nested/pyproject.toml",
3505 "[tool.autoflake]\n",
3506 )
3507 self.create_file(
3508 "pyproject.toml",
3509 "[tool.autoflake]\nexpand-star-imports = true\n",
3510 )
3511 files = [self.effective_path("nested/test_me.py")]
3512 args, success = autoflake.merge_configuration_file({"files": files})
3513 assert success is True
3514 assert args == self.with_defaults(files=files)
3515
3516 def test_config_option(self) -> None:
3517 with temporary_file(
3518 suffix=".ini",
3519 contents=("[autoflake]\ncheck = True\n"),
3520 ) as temp_config:
3521 self.create_file("test_me.py")
3522 files = [self.effective_path("test_me.py")]
3523
3524 args, success = autoflake.merge_configuration_file(
3525 {
3526 "files": files,
3527 "config_file": temp_config,
3528 },
3529 )
3530 assert success is True
3531 assert args == self.with_defaults(
3532 files=files,
3533 config_file=temp_config,
3534 check=True,
3535 )
3536
3537 def test_merge_configuration_file__toml_config_option(self) -> None:
3538 with temporary_file(
3539 suffix=".toml",
3540 contents=("[tool.autoflake]\ncheck = true\n"),
3541 ) as temp_config:
3542 self.create_file("test_me.py")
3543 files = [self.effective_path("test_me.py")]
3544
3545 args, success = autoflake.merge_configuration_file(
3546 {
3547 "files": files,
3548 "config_file": temp_config,
3549 },
3550 )
3551
3552 assert success is True
3553 assert args == self.with_defaults(
3554 files=files,
3555 config_file=temp_config,
3556 check=True,
3557 )
3558
3559 def test_load_false(self) -> None:
3560 self.create_file("test_me.py")
3561 self.create_file(
3562 "setup.cfg",
3563 "[autoflake]\nexpand-star-imports = no\n",
3564 )
3565 files = [self.effective_path("test_me.py")]
3566
3567 args, success = autoflake.merge_configuration_file({"files": files})
3568 assert success is True
3569 assert args == self.with_defaults(
3570 files=files,
3571 expand_star_imports=False,
3572 )
3573
3574 def test_list_value_pyproject_toml(self) -> None:
3575 self.create_file("test_me.py")
3576 self.create_file(
3577 "pyproject.toml",
3578 '[tool.autoflake]\nimports=["my_lib", "other_lib"]\n',
3579 )
3580 files = [self.effective_path("test_me.py")]
3581 args, success = autoflake.merge_configuration_file({"files": files})
3582 assert success is True
3583 assert args == self.with_defaults(
3584 files=files,
3585 imports="my_lib,other_lib",
3586 )
3587
3588 def test_list_value_comma_sep_string_pyproject_toml(self) -> None:
3589 self.create_file("test_me.py")
3590 self.create_file(
3591 "pyproject.toml",
3592 '[tool.autoflake]\nimports="my_lib,other_lib"\n',
3593 )
3594 files = [self.effective_path("test_me.py")]
3595 args, success = autoflake.merge_configuration_file({"files": files})
3596 assert success is True
3597 assert args == self.with_defaults(
3598 files=files,
3599 imports="my_lib,other_lib",
3600 )
3601
3602 def test_list_value_setup_cfg(self) -> None:
3603 self.create_file("test_me.py")
3604 self.create_file(
3605 "setup.cfg",
3606 "[autoflake]\nimports=my_lib,other_lib\n",
3607 )
3608 files = [self.effective_path("test_me.py")]
3609 args, success = autoflake.merge_configuration_file({"files": files})
3610 assert success is True
3611 assert args == self.with_defaults(
3612 files=files,
3613 imports="my_lib,other_lib",
3614 )
3615
3616 def test_non_bool_value_for_bool_property(self) -> None:
3617 self.create_file("test_me.py")
3618 self.create_file(
3619 "pyproject.toml",
3620 '[tool.autoflake]\nexpand-star-imports="invalid"\n',
3621 )
3622 files = [self.effective_path("test_me.py")]
3623 _, success = autoflake.merge_configuration_file({"files": files})
3624 assert success is False
3625
3626 def test_non_bool_value_for_bool_property_in_setup_cfg(self) -> None:
3627 self.create_file("test_me.py")
3628 self.create_file(
3629 "setup.cfg",
3630 "[autoflake]\nexpand-star-imports=ok\n",
3631 )
3632 files = [self.effective_path("test_me.py")]
3633 _, success = autoflake.merge_configuration_file({"files": files})
3634 assert success is False
3635
3636 def test_non_list_value_for_list_property(self) -> None:
3637 self.create_file("test_me.py")
3638 self.create_file(
3639 "pyproject.toml",
3640 "[tool.autoflake]\nexclude=true\n",
3641 )
3642 files = [self.effective_path("test_me.py")]
3643 _, success = autoflake.merge_configuration_file({"files": files})
3644 assert success is False
3645
3646 def test_merge_with_cli_set_list_property(self) -> None:
3647 self.create_file("test_me.py")
3648 self.create_file(
3649 "pyproject.toml",
3650 '[tool.autoflake]\nimports=["my_lib"]\n',
3651 )
3652 files = [self.effective_path("test_me.py")]
3653 args, success = autoflake.merge_configuration_file(
3654 {"files": files, "imports": "other_lib"},
3655 )
3656 assert success is True
3657 assert args == self.with_defaults(
3658 files=files,
3659 imports="my_lib,other_lib",
3660 )
3661
3662 def test_merge_prioritizes_flags(self) -> None:
3663 self.create_file("test_me.py")
3664 self.create_file(
3665 "pyproject.toml",
3666 "[tool.autoflake]\ncheck = false\n",
3667 )
3668 files = [self.effective_path("test_me.py")]
3669 flag_args = {
3670 "files": files,
3671 "imports": "other_lib",
3672 "check": True,
3673 }
3674 args, success = autoflake.merge_configuration_file(flag_args)
3675 assert success is True
3676 assert args == self.with_defaults(
3677 files=files,
3678 imports="other_lib",
3679 check=True,
3680 )
3681
3682
3683 @contextlib.contextmanager
3684 def temporary_file(
3685 contents: str,
3686 directory: str = ".",
3687 suffix: str = ".py",
3688 prefix: str = "",
3689 ) -> Iterator[str]:
3690 """Write contents to temporary file and yield it."""
3691 f = tempfile.NamedTemporaryFile(
3692 suffix=suffix,
3693 prefix=prefix,
3694 delete=False,
3695 dir=directory,
3696 )
3697 try:
3698 f.write(contents.encode())
3699 f.close()
3700 yield f.name
3701 finally:
3702 os.remove(f.name)
3703
3704
3705 @contextlib.contextmanager
3706 def temporary_directory(directory: str = ".", prefix: str = "tmp.") -> Iterator[str]:
3707 """Create temporary directory and yield its path."""
3708 temp_directory = tempfile.mkdtemp(prefix=prefix, dir=directory)
3709 try:
3710 yield temp_directory
3711 finally:
3712 shutil.rmtree(temp_directory)
3713
3714
3715 class StubFile:
3716 """Fake file that ignores everything."""
3717
3718 def write(*_: Any) -> None:
3719 """Ignore."""
3720
3721
3722 if __name__ == "__main__":
3723 unittest.main()