Debian Codegraph @

tests/unit/test_settings.py

raw
1 import os
2 import sys
3 from pathlib import Path
4
5 import pytest
6
7 from isort import code, exceptions, place_module, settings
8 from isort.settings import Config
9 from isort.wrap_modes import WrapModes
10
11
12 class TestConfig:
13 instance = Config()
14
15 def test_init(self) -> None:
16 assert Config()
17
18 def test_init_unsupported_settings_fails_gracefully(self) -> None:
19 with pytest.raises(exceptions.UnsupportedSettings):
20 Config(apply=True)
21 with pytest.raises(exceptions.UnsupportedSettings) as error:
22 Config(apply=True)
23 assert error.value.unsupported_settings == {"apply": {"value": True, "source": "runtime"}}
24
25 def test_known_settings(self) -> None:
26 assert Config(known_third_party=["one"]).known_third_party == frozenset({"one"})
27 assert Config(known_thirdparty=["two"]).known_third_party == frozenset({"two"})
28 assert Config(
29 known_third_party=["one"], known_thirdparty=["two"]
30 ).known_third_party == frozenset({"one"})
31
32 def test_invalid_settings_path(self) -> None:
33 with pytest.raises(exceptions.InvalidSettingsPath):
34 Config(settings_path="this_couldnt_possibly_actually_exists/could_it")
35
36 def test_invalid_pyversion(self) -> None:
37 with pytest.raises(ValueError, match=r"The python version 10 is not supported."):
38 Config(py_version=10)
39
40 def test_invalid_profile(self) -> None:
41 with pytest.raises(exceptions.ProfileDoesNotExist):
42 Config(profile="blackandwhitestylemixedwithpep8")
43
44 def test_is_skipped(self) -> None:
45 assert Config().is_skipped(Path("C:\\path\\isort.py"))
46 assert Config(skip=["/path/isort.py"]).is_skipped(Path("C:\\path\\isort.py"))
47
48 def test_is_supported_filetype(self) -> None:
49 assert self.instance.is_supported_filetype("file.py")
50 assert self.instance.is_supported_filetype("file.pyi")
51 assert self.instance.is_supported_filetype("file.pyx")
52 assert self.instance.is_supported_filetype("file.pxd")
53 assert not self.instance.is_supported_filetype("file.pyc")
54 assert not self.instance.is_supported_filetype("file.txt")
55 assert not self.instance.is_supported_filetype("file.pex")
56
57 def test_is_supported_filetype_ioerror(self, tmp_path: Path) -> None:
58 does_not_exist = tmp_path / "fake.txt"
59 assert not self.instance.is_supported_filetype(str(does_not_exist))
60
61 def test_is_supported_filetype_shebang(self, tmp_path: Path) -> None:
62 path = tmp_path / "myscript"
63 path.write_text("#!/usr/bin/env python\n")
64 assert self.instance.is_supported_filetype(str(path))
65
66 def test_is_supported_filetype_editor_backup(self, tmp_path: Path) -> None:
67 path = tmp_path / "myscript~"
68 path.write_text("#!/usr/bin/env python\n")
69 assert not self.instance.is_supported_filetype(str(path))
70
71 def test_is_supported_filetype_defaults(self, tmp_path: Path) -> None:
72 assert self.instance.is_supported_filetype(str(tmp_path / "stub.pyi"))
73 assert self.instance.is_supported_filetype(str(tmp_path / "source.py"))
74 assert self.instance.is_supported_filetype(str(tmp_path / "source.pyx"))
75
76 def test_is_supported_filetype_configuration(self, tmp_path: Path) -> None:
77 config = Config(supported_extensions=("pyx",), blocked_extensions=("py",))
78 assert config.is_supported_filetype(str(tmp_path / "stub.pyx"))
79 assert not config.is_supported_filetype(str(tmp_path / "stub.py"))
80
81 @pytest.mark.skipif(
82 sys.platform == "win32", reason="cannot create fifo file on Windows platform"
83 )
84 def test_is_supported_filetype_fifo(self, tmp_path: Path) -> None:
85 fifo_file = str(tmp_path / "fifo_file")
86 os.mkfifo(fifo_file)
87 assert not self.instance.is_supported_filetype(fifo_file)
88
89 def test_src_paths_are_combined_and_deduplicated(self) -> None:
90 src_paths = ["src", "tests"]
91 src_full_paths = (Path(os.getcwd()) / f for f in src_paths)
92 assert sorted(Config(src_paths=src_paths * 2).src_paths) == sorted(src_full_paths)
93
94 def test_src_paths_supports_glob_expansion(self, tmp_path: Path) -> None:
95 libs = tmp_path / "libs"
96 libs.mkdir()
97 requests = libs / "requests"
98 requests.mkdir()
99 beautifulpasta = libs / "beautifulpasta"
100 beautifulpasta.mkdir()
101 assert sorted(Config(directory=tmp_path, src_paths=["libs/*"]).src_paths) == sorted(
102 (beautifulpasta, requests)
103 )
104
105 def test_deprecated_multi_line_output(self) -> None:
106 assert Config(multi_line_output=6).multi_line_output == WrapModes.VERTICAL_GRID_GROUPED # noqa
107
108
109 def test_as_list() -> None:
110 assert settings._as_list([" one "]) == ["one"]
111 assert settings._as_list("one,two") == ["one", "two"]
112
113
114 def _write_simple_settings(tmp_file: Path) -> None:
115 tmp_file.write_text(
116 """
117 [isort]
118 force_grid_wrap=true
119 """,
120 "utf8",
121 )
122
123
124 def test_find_config(tmp_path: Path) -> None:
125 tmp_config = tmp_path / ".isort.cfg"
126
127 # can't find config if it has no relevant section
128 tmp_config.write_text(
129 """
130 [section]
131 force_grid_wrap=true
132 """,
133 "utf8",
134 )
135 assert not settings._find_config(str(tmp_path))[1]
136
137 # or if it is malformed
138 tmp_config.write_text("""arstoyrsyan arienrsaeinrastyngpuywnlguyn354q^%$)(%_)@$""", "utf8")
139 assert not settings._find_config(str(tmp_path))[1]
140
141 # can when it has either a file format, or generic relevant section
142 _write_simple_settings(tmp_config)
143 assert settings._find_config(str(tmp_path))[1]
144
145
146 def test_find_config_deep(tmp_path: Path) -> None:
147 # can't find config if it is further up than MAX_CONFIG_SEARCH_DEPTH
148 dirs = [f"dir{i}" for i in range(settings.MAX_CONFIG_SEARCH_DEPTH + 1)]
149 tmp_dirs = tmp_path.joinpath(*dirs)
150 tmp_dirs.mkdir(parents=True)
151 tmp_config = tmp_path / "dir0" / ".isort.cfg"
152 _write_simple_settings(tmp_config)
153 assert not settings._find_config(str(tmp_dirs))[1]
154 # but can find config if it is MAX_CONFIG_SEARCH_DEPTH up
155 one_parent_up = os.path.split(str(tmp_dirs))[0]
156 assert settings._find_config(one_parent_up)[1]
157
158
159 @pytest.mark.parametrize(
160 ("marker", "is_directory", "is_repository"),
161 [
162 (".git", True, True),
163 (".git", False, True),
164 (".hg", True, True),
165 (".hg", False, False),
166 (None, False, False),
167 ],
168 )
169 def test_find_config_stops_at_repository_boundary(
170 tmp_path: Path, marker: str | None, is_directory: bool, is_repository: bool
171 ) -> None:
172 outer_config = tmp_path / ".isort.cfg"
173 _write_simple_settings(outer_config)
174 project = tmp_path / "project"
175 nested = project / "nested"
176 nested.mkdir(parents=True)
177 if is_directory and marker is not None:
178 (project / marker).mkdir()
179 elif marker:
180 (project / marker).write_text("gitdir: ../main/.git/worktrees/project\n", encoding="utf8")
181
182 root, config = settings._find_config(str(nested))
183 if is_repository:
184 assert root == str(project)
185 assert config == {}
186 else:
187 assert root == str(tmp_path)
188 assert config["source"] == str(outer_config)
189
190
191 @pytest.mark.parametrize("config_location", ["outer", "project", "nested"])
192 def test_find_config_in_git_worktree(
193 tmp_path: Path, monkeypatch: pytest.MonkeyPatch, config_location: str
194 ) -> None:
195 outer_config = tmp_path / ".isort.cfg"
196 outer_config.write_text("[settings]\nline_length = 42\n", encoding="utf8")
197 project = tmp_path / "project"
198 nested = project / "nested"
199 nested.mkdir(parents=True)
200 (project / ".git").write_text("gitdir: ../main/.git/worktrees/project\n", encoding="utf8")
201 (project / "local_module.py").touch()
202 monkeypatch.chdir(project)
203
204 if config_location != "outer":
205 config_directory = project if config_location == "project" else nested
206 config_file = config_directory / ".isort.cfg"
207 config_file.write_text("[settings]\nline_length = 88\n", encoding="utf8")
208 assert settings._find_config(str(nested))[1]["source"] == str(config_file)
209 else:
210 config = Config(settings_path=str(nested))
211 assert config.line_length == settings.DEFAULT_CONFIG.line_length
212 assert place_module("local_module", config=config) == "FIRSTPARTY"
213 source = "import third_party\n\nimport local_module\n"
214 assert code(source, config=config) == source
215
216
217 def test_get_config_data(tmp_path: Path) -> None:
218 test_config = tmp_path / "test_config.editorconfig"
219 test_config.write_text(
220 """
221 root = true
222
223 [*.{js,py}]
224 indent_style=tab
225 indent_size=tab
226
227 [*.py]
228 force_grid_wrap=false
229 comment_prefix="text"
230
231 [*.{java}]
232 indent_style = space
233 """,
234 "utf8",
235 )
236 loaded_settings = settings._get_config_data(
237 str(test_config), sections=settings.CONFIG_SECTIONS[".editorconfig"]
238 )
239 assert loaded_settings
240 assert loaded_settings["comment_prefix"] == "text"
241 assert loaded_settings["force_grid_wrap"] == 0
242 assert loaded_settings["indent"] == "\t"
243 assert isinstance(loaded_settings["source"], str)
244 assert str(tmp_path) in loaded_settings["source"]
245
246
247 def test_editorconfig_without_sections(tmp_path: Path) -> None:
248 test_config = tmp_path / "test_config.editorconfig"
249 test_config.write_text("\nroot = true\n", "utf8")
250 loaded_settings = settings._get_config_data(str(test_config), sections=("*.py",))
251 assert not loaded_settings
252
253
254 def test_get_config_data_with_toml_and_utf8(tmp_path: Path) -> None:
255 test_config = tmp_path / "pyproject.toml"
256 # Exception: UnicodeDecodeError: 'gbk' codec can't decode byte 0x84 in position 57
257 test_config.write_text(
258 """
259 [project]
260 description = "基于FastAPI + Mysql的 TodoList" # Exception: UnicodeDecodeError
261 name = "TodoList"
262 version = "0.1.0"
263
264 [tool.isort]
265 multi_line_output = 3
266
267 """,
268 "utf8",
269 )
270 loaded_settings = settings._get_config_data(
271 str(test_config), sections=settings.CONFIG_SECTIONS["pyproject.toml"]
272 )
273 assert loaded_settings
274 assert isinstance(loaded_settings["source"], str)
275 assert str(tmp_path) in loaded_settings["source"]
276
277
278 def test_as_bool() -> None:
279 assert settings._as_bool("TrUe") is True
280 assert settings._as_bool("true") is True
281 assert settings._as_bool("t") is True
282 assert settings._as_bool("FALSE") is False
283 assert settings._as_bool("faLSE") is False
284 assert settings._as_bool("f") is False
285 with pytest.raises(ValueError, match="invalid truth value"):
286 settings._as_bool("")
287 with pytest.raises(ValueError, match="invalid truth value falsey"):
288 settings._as_bool("falsey")
289 with pytest.raises(ValueError, match="invalid truth value truthy"):
290 settings._as_bool("truthy")
291
292
293 def test_find_all_configs(tmp_path: Path) -> None:
294 setup_cfg = """
295 [isort]
296 profile=django
297 """
298
299 pyproject_toml = """
300 [tool.isort]
301 profile = "hug"
302 """
303
304 isort_cfg = """
305 [settings]
306 profile=black
307 """
308
309 pyproject_toml_broken = """
310 [tool.isorts]
311 something = nothing
312 """
313
314 dir1 = tmp_path / "subdir1"
315 dir2 = tmp_path / "subdir2"
316 dir3 = tmp_path / "subdir3"
317 dir4 = tmp_path / "subdir4"
318
319 dir1.mkdir()
320 dir2.mkdir()
321 dir3.mkdir()
322 dir4.mkdir()
323
324 setup_cfg_file = dir1 / "setup.cfg"
325 setup_cfg_file.write_text(setup_cfg, "utf-8")
326
327 pyproject_toml_file = dir2 / "pyproject.toml"
328 pyproject_toml_file.write_text(pyproject_toml, "utf-8")
329
330 isort_cfg_file = dir3 / ".isort.cfg"
331 isort_cfg_file.write_text(isort_cfg, "utf-8")
332
333 pyproject_toml_file_broken = dir4 / "pyproject.toml"
334 pyproject_toml_file_broken.write_text(pyproject_toml_broken, "utf-8")
335
336 config_trie = settings.find_all_configs(str(tmp_path))
337
338 config_info_1 = config_trie.search(str(dir1 / "test1.py"))
339 assert config_info_1[0] == str(setup_cfg_file)
340 assert config_info_1[0] == str(setup_cfg_file)
341 assert config_info_1[1]["profile"] == "django"
342
343 config_info_2 = config_trie.search(str(dir2 / "test2.py"))
344 assert config_info_2[0] == str(pyproject_toml_file)
345 assert config_info_2[0] == str(pyproject_toml_file)
346 assert config_info_2[1]["profile"] == "hug"
347
348 config_info_3 = config_trie.search(str(dir3 / "test3.py"))
349 assert config_info_3[0] == str(isort_cfg_file)
350 assert config_info_3[0] == str(isort_cfg_file)
351 assert config_info_3[1]["profile"] == "black"
352
353 config_info_4 = config_trie.search(str(tmp_path / "file4.py"))
354 assert config_info_4[0] == "default"