Debian Codegraph @

testing/test_findpaths.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import os
5 from pathlib import Path
6 from textwrap import dedent
7
8 from _pytest.config import UsageError
9 from _pytest.config.findpaths import ConfigValue
10 from _pytest.config.findpaths import get_common_ancestor
11 from _pytest.config.findpaths import get_dirs_from_args
12 from _pytest.config.findpaths import is_fs_root
13 from _pytest.config.findpaths import load_config_dict_from_file
14 import pytest
15
16
17 class TestLoadConfigDictFromFile:
18 @pytest.mark.parametrize("filename", ["pytest.ini", ".pytest.ini"])
19 def test_empty_pytest_ini(self, tmp_path: Path, filename: str) -> None:
20 """pytest.ini files are always considered for configuration, even if empty"""
21 fn = tmp_path / filename
22 fn.write_text("", encoding="utf-8")
23 assert load_config_dict_from_file(fn) == {}
24
25 def test_pytest_ini(self, tmp_path: Path) -> None:
26 """[pytest] section in pytest.ini files is read correctly"""
27 fn = tmp_path / "pytest.ini"
28 fn.write_text("[pytest]\nx=1", encoding="utf-8")
29 assert load_config_dict_from_file(fn) == {
30 "x": ConfigValue("1", origin="file", mode="ini")
31 }
32
33 def test_custom_ini(self, tmp_path: Path) -> None:
34 """[pytest] section in any .ini file is read correctly"""
35 fn = tmp_path / "custom.ini"
36 fn.write_text("[pytest]\nx=1", encoding="utf-8")
37 assert load_config_dict_from_file(fn) == {
38 "x": ConfigValue("1", origin="file", mode="ini")
39 }
40
41 def test_custom_ini_without_section(self, tmp_path: Path) -> None:
42 """Custom .ini files without [pytest] section are not considered for configuration"""
43 fn = tmp_path / "custom.ini"
44 fn.write_text("[custom]", encoding="utf-8")
45 assert load_config_dict_from_file(fn) is None
46
47 def test_custom_cfg_file(self, tmp_path: Path) -> None:
48 """Custom .cfg files without [tool:pytest] section are not considered for configuration"""
49 fn = tmp_path / "custom.cfg"
50 fn.write_text("[custom]", encoding="utf-8")
51 assert load_config_dict_from_file(fn) is None
52
53 def test_valid_cfg_file(self, tmp_path: Path) -> None:
54 """Custom .cfg files with [tool:pytest] section are read correctly"""
55 fn = tmp_path / "custom.cfg"
56 fn.write_text("[tool:pytest]\nx=1", encoding="utf-8")
57 assert load_config_dict_from_file(fn) == {
58 "x": ConfigValue("1", origin="file", mode="ini")
59 }
60
61 def test_unsupported_pytest_section_in_cfg_file(self, tmp_path: Path) -> None:
62 """.cfg files with [pytest] section are no longer supported and should fail to alert users"""
63 fn = tmp_path / "custom.cfg"
64 fn.write_text("[pytest]", encoding="utf-8")
65 with pytest.raises(pytest.fail.Exception):
66 load_config_dict_from_file(fn)
67
68 def test_invalid_toml_file(self, tmp_path: Path) -> None:
69 """Invalid .toml files should raise `UsageError`."""
70 fn = tmp_path / "myconfig.toml"
71 fn.write_text("]invalid toml[", encoding="utf-8")
72 with pytest.raises(UsageError):
73 load_config_dict_from_file(fn)
74
75 def test_custom_toml_file(self, tmp_path: Path) -> None:
76 """.toml files without [tool.pytest] are not considered for configuration."""
77 fn = tmp_path / "myconfig.toml"
78 fn.write_text(
79 dedent(
80 """
81 [build_system]
82 x = 1
83 """
84 ),
85 encoding="utf-8",
86 )
87 assert load_config_dict_from_file(fn) is None
88
89 def test_valid_toml_file(self, tmp_path: Path) -> None:
90 """.toml files with [tool.pytest.ini_options] are read correctly, including changing
91 data types to str/list for compatibility with other configuration options."""
92 fn = tmp_path / "myconfig.toml"
93 fn.write_text(
94 dedent(
95 """
96 [tool.pytest.ini_options]
97 x = 1
98 y = 20.0
99 values = ["tests", "integration"]
100 name = "foo"
101 heterogeneous_array = [1, "str"]
102 """
103 ),
104 encoding="utf-8",
105 )
106 assert load_config_dict_from_file(fn) == {
107 "x": ConfigValue("1", origin="file", mode="ini"),
108 "y": ConfigValue("20.0", origin="file", mode="ini"),
109 "values": ConfigValue(["tests", "integration"], origin="file", mode="ini"),
110 "name": ConfigValue("foo", origin="file", mode="ini"),
111 "heterogeneous_array": ConfigValue([1, "str"], origin="file", mode="ini"),
112 }
113
114 def test_native_toml_config(self, tmp_path: Path) -> None:
115 """[tool.pytest] sections with native types are parsed correctly without coercion."""
116 fn = tmp_path / "pyproject.toml"
117 fn.write_text(
118 dedent(
119 """
120 [tool.pytest]
121 minversion = "7.0"
122 xfail_strict = true
123 testpaths = ["tests", "integration"]
124 python_files = ["test_*.py", "*_test.py"]
125 verbosity_assertions = 2
126 maxfail = 5
127 timeout = 300.5
128 """
129 ),
130 encoding="utf-8",
131 )
132 result = load_config_dict_from_file(fn)
133 assert result == {
134 "minversion": ConfigValue("7.0", origin="file", mode="toml"),
135 "xfail_strict": ConfigValue(True, origin="file", mode="toml"),
136 "testpaths": ConfigValue(
137 ["tests", "integration"], origin="file", mode="toml"
138 ),
139 "python_files": ConfigValue(
140 ["test_*.py", "*_test.py"], origin="file", mode="toml"
141 ),
142 "verbosity_assertions": ConfigValue(2, origin="file", mode="toml"),
143 "maxfail": ConfigValue(5, origin="file", mode="toml"),
144 "timeout": ConfigValue(300.5, origin="file", mode="toml"),
145 }
146
147 def test_native_and_ini_conflict(self, tmp_path: Path) -> None:
148 """Using both [tool.pytest] and [tool.pytest.ini_options] should raise an error."""
149 fn = tmp_path / "pyproject.toml"
150 fn.write_text(
151 dedent(
152 """
153 [tool.pytest]
154 xfail_strict = true
155
156 [tool.pytest.ini_options]
157 minversion = "7.0"
158 """
159 ),
160 encoding="utf-8",
161 )
162 with pytest.raises(UsageError, match="Cannot use both"):
163 load_config_dict_from_file(fn)
164
165 def test_invalid_suffix(self, tmp_path: Path) -> None:
166 """A file with an unknown suffix is ignored."""
167 fn = tmp_path / "pytest.config"
168 fn.write_text("", encoding="utf-8")
169 assert load_config_dict_from_file(fn) is None
170
171
172 class TestCommonAncestor:
173 def test_has_ancestor(self, tmp_path: Path) -> None:
174 fn1 = tmp_path / "foo" / "bar" / "test_1.py"
175 fn1.parent.mkdir(parents=True)
176 fn1.touch()
177 fn2 = tmp_path / "foo" / "zaz" / "test_2.py"
178 fn2.parent.mkdir(parents=True)
179 fn2.touch()
180 cwd = Path.cwd()
181 assert get_common_ancestor(cwd, [fn1, fn2]) == tmp_path / "foo"
182 assert get_common_ancestor(cwd, [fn1.parent, fn2]) == tmp_path / "foo"
183 assert get_common_ancestor(cwd, [fn1.parent, fn2.parent]) == tmp_path / "foo"
184 assert get_common_ancestor(cwd, [fn1, fn2.parent]) == tmp_path / "foo"
185
186 def test_single_dir(self, tmp_path: Path) -> None:
187 assert get_common_ancestor(Path.cwd(), [tmp_path]) == tmp_path
188
189 def test_single_file(self, tmp_path: Path) -> None:
190 fn = tmp_path / "foo.py"
191 fn.touch()
192 assert get_common_ancestor(Path.cwd(), [fn]) == tmp_path
193
194
195 def test_get_dirs_from_args(tmp_path):
196 """get_dirs_from_args() skips over non-existing directories and files"""
197 fn = tmp_path / "foo.py"
198 fn.touch()
199 d = tmp_path / "tests"
200 d.mkdir()
201 option = "--foobar=/foo.txt"
202 # xdist uses options in this format for its rsync feature (#7638)
203 xdist_rsync_option = "popen=c:/dest"
204 assert get_dirs_from_args(
205 [str(fn), str(tmp_path / "does_not_exist"), str(d), option, xdist_rsync_option]
206 ) == [fn.parent, d]
207
208
209 @pytest.mark.parametrize(
210 "path, expected",
211 [
212 pytest.param(
213 f"e:{os.sep}", True, marks=pytest.mark.skipif("sys.platform != 'win32'")
214 ),
215 (f"{os.sep}", True),
216 (f"e:{os.sep}projects", False),
217 (f"{os.sep}projects", False),
218 ],
219 )
220 def test_is_fs_root(path: Path, expected: bool) -> None:
221 assert is_fs_root(Path(path)) is expected