Debian Codegraph @

tests/unit/test_format.py

raw
1 from io import StringIO
2 from pathlib import Path
3 from unittest.mock import MagicMock, patch
4
5 import colorama
6 import pytest
7 from hypothesis import given, reject
8 from hypothesis import strategies as st
9
10 import isort.format
11
12
13 def test_ask_whether_to_apply_changes_to_file() -> None:
14 with patch("builtins.input", MagicMock(return_value="y")):
15 assert isort.format.ask_whether_to_apply_changes_to_file("")
16 with patch("builtins.input", MagicMock(return_value="n")):
17 assert not isort.format.ask_whether_to_apply_changes_to_file("")
18 with patch("builtins.input", MagicMock(return_value="q")):
19 with pytest.raises(SystemExit):
20 assert isort.format.ask_whether_to_apply_changes_to_file("")
21
22
23 def test_ask_whether_to_apply_changes_to_file_eof_is_treated_as_quit() -> None:
24 # Regression test for #1897: a closed/exhausted stdin (input() raising EOFError)
25 # must exit cleanly like an explicit "quit" answer, not propagate as an
26 # unhandled exception that main.py reports as an "unrecoverable exception".
27 with patch("builtins.input", MagicMock(side_effect=EOFError)):
28 with pytest.raises(SystemExit):
29 isort.format.ask_whether_to_apply_changes_to_file("")
30
31
32 def test_basic_printer(capsys: pytest.CaptureFixture[str]) -> None:
33 printer = isort.format.create_terminal_printer(
34 color=False, success="{success}: {message}", error="{error}: {message}"
35 )
36 printer.success("All good!")
37 out, _ = capsys.readouterr()
38 assert out == "SUCCESS: All good!\n"
39 printer.error("Some error")
40 _, err = capsys.readouterr()
41 assert err == "ERROR: Some error\n"
42
43 printer = isort.format.create_terminal_printer(
44 color=False, success="success: {message}: {success}", error="error: {message}: {error}"
45 )
46 printer.success("All good!")
47 out, _ = capsys.readouterr()
48 assert out == "success: All good!: SUCCESS\n"
49 printer.error("Some error")
50 _, err = capsys.readouterr()
51 assert err == "error: Some error: ERROR\n"
52
53
54 def test_basic_printer_diff(capsys: pytest.CaptureFixture[str]) -> None:
55 printer = isort.format.create_terminal_printer(color=False)
56 printer.diff_line("+ added line\n")
57 printer.diff_line("- removed line\n")
58
59 out, _ = capsys.readouterr()
60 assert out == "+ added line\n- removed line\n"
61
62
63 def test_colored_printer_success(capsys: pytest.CaptureFixture[str]) -> None:
64 printer = isort.format.create_terminal_printer(color=True, success="{success}: {message}")
65 printer.success("All good!")
66 out, _ = capsys.readouterr()
67 assert "SUCCESS" in out
68 assert "All good!" in out
69 assert colorama.Fore.GREEN in out
70
71
72 def test_colored_printer_error(capsys: pytest.CaptureFixture[str]) -> None:
73 printer = isort.format.create_terminal_printer(color=True, error="{error}: {message}")
74 printer.error("Some error")
75 _, err = capsys.readouterr()
76 assert "ERROR" in err
77 assert "Some error" in err
78 assert colorama.Fore.RED in err
79
80
81 def test_colored_printer_diff(capsys: pytest.CaptureFixture[str]) -> None:
82 printer = isort.format.create_terminal_printer(color=True)
83 printer.diff_line("+++ file1\n")
84 printer.diff_line("--- file2\n")
85 printer.diff_line("+ added line\n")
86 printer.diff_line("normal line\n")
87 printer.diff_line("- removed line\n")
88 printer.diff_line("normal line\n")
89
90 out, _ = capsys.readouterr()
91 # No color added to lines with multiple + and -'s
92 assert out.startswith("+++ file1\n--- file2\n")
93 # Added lines are green
94 assert colorama.Fore.GREEN + "+ added line" in out
95 # Removed lines are red
96 assert colorama.Fore.RED + "- removed line" in out
97 # Normal lines are reset back
98 assert colorama.Style.RESET_ALL + "normal line" in out
99
100
101 def test_colored_printer_diff_output(capsys: pytest.CaptureFixture[str]) -> None:
102 output = StringIO()
103 printer = isort.format.create_terminal_printer(color=True, output=output)
104 printer.diff_line("a line\n")
105
106 out, _ = capsys.readouterr()
107 assert out == ""
108
109 output.seek(0)
110 assert output.read().startswith("a line\n")
111
112
113 @patch("isort.format.colorama_unavailable", True)
114 def test_colorama_not_available_handled_gracefully(capsys: pytest.CaptureFixture[str]) -> None:
115 with pytest.raises(SystemExit) as system_exit:
116 _ = isort.format.create_terminal_printer(color=True)
117 assert system_exit.value.code
118 assert int(system_exit.value.code) > 0
119 _, err = capsys.readouterr()
120 assert "colorama" in err
121 assert "colors extra" in err
122
123
124 # This test code was written by the `hypothesis.extra.ghostwriter` module
125 # and is provided under the Creative Commons Zero public domain dedication.
126
127
128 @given(
129 file_input=st.text(),
130 file_output=st.text(),
131 file_path=st.one_of(st.none(), st.builds(Path)),
132 output=st.one_of(st.none(), st.builds(StringIO, st.text())),
133 )
134 def test_fuzz_show_unified_diff(
135 file_input: str, file_output: str, file_path: Path | None, output: StringIO | None
136 ) -> None:
137 try:
138 isort.format.show_unified_diff(
139 file_input=file_input,
140 file_output=file_output,
141 file_path=file_path,
142 output=output,
143 )
144 except UnicodeEncodeError:
145 reject()