Debian Codegraph @

testing/test_main.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import argparse
5 import os
6 from pathlib import Path
7 import re
8
9 from _pytest.config import ExitCode
10 from _pytest.config import UsageError
11 from _pytest.main import CollectionArgument
12 from _pytest.main import resolve_collection_argument
13 from _pytest.main import validate_basetemp
14 from _pytest.pytester import Pytester
15 import pytest
16
17
18 @pytest.mark.parametrize(
19 "ret_exc",
20 (
21 pytest.param((None, ValueError)),
22 pytest.param((42, SystemExit)),
23 pytest.param((False, SystemExit)),
24 ),
25 )
26 def test_wrap_session_notify_exception(ret_exc, pytester: Pytester) -> None:
27 returncode, exc = ret_exc
28 c1 = pytester.makeconftest(
29 f"""
30 import pytest
31
32 def pytest_sessionstart():
33 raise {exc.__name__}("boom")
34
35 def pytest_internalerror(excrepr, excinfo):
36 returncode = {returncode!r}
37 if returncode is not False:
38 pytest.exit("exiting after %s..." % excinfo.typename, returncode={returncode!r})
39 """
40 )
41 result = pytester.runpytest()
42 if returncode:
43 assert result.ret == returncode
44 else:
45 assert result.ret == ExitCode.INTERNAL_ERROR
46 assert result.stdout.lines[0] == "INTERNALERROR> Traceback (most recent call last):"
47
48 end_lines = result.stdout.lines[-3:]
49
50 if exc == SystemExit:
51 assert end_lines == [
52 f'INTERNALERROR> File "{c1}", line 4, in pytest_sessionstart',
53 'INTERNALERROR> raise SystemExit("boom")',
54 "INTERNALERROR> SystemExit: boom",
55 ]
56 else:
57 assert end_lines == [
58 f'INTERNALERROR> File "{c1}", line 4, in pytest_sessionstart',
59 'INTERNALERROR> raise ValueError("boom")',
60 "INTERNALERROR> ValueError: boom",
61 ]
62 if returncode is False:
63 assert result.stderr.lines == ["mainloop: caught unexpected SystemExit!"]
64 else:
65 assert result.stderr.lines == [f"Exit: exiting after {exc.__name__}..."]
66
67
68 @pytest.mark.parametrize("returncode", (None, 42))
69 def test_wrap_session_exit_sessionfinish(
70 returncode: int | None, pytester: Pytester
71 ) -> None:
72 pytester.makeconftest(
73 f"""
74 import pytest
75 def pytest_sessionfinish():
76 pytest.exit(reason="exit_pytest_sessionfinish", returncode={returncode})
77 """
78 )
79 result = pytester.runpytest()
80 if returncode:
81 assert result.ret == returncode
82 else:
83 assert result.ret == ExitCode.NO_TESTS_COLLECTED
84 assert result.stdout.lines[-1] == "collected 0 items"
85 assert result.stderr.lines == ["Exit: exit_pytest_sessionfinish"]
86
87
88 @pytest.mark.parametrize("basetemp", ["foo", "foo/bar"])
89 def test_validate_basetemp_ok(tmp_path, basetemp, monkeypatch):
90 monkeypatch.chdir(str(tmp_path))
91 validate_basetemp(tmp_path / basetemp)
92
93
94 @pytest.mark.parametrize("basetemp", ["", ".", ".."])
95 def test_validate_basetemp_fails(tmp_path, basetemp, monkeypatch):
96 monkeypatch.chdir(str(tmp_path))
97 msg = "basetemp must not be empty, the current working directory or any parent directory of it"
98 with pytest.raises(argparse.ArgumentTypeError, match=msg):
99 if basetemp:
100 basetemp = tmp_path / basetemp
101 validate_basetemp(basetemp)
102
103
104 def test_validate_basetemp_integration(pytester: Pytester) -> None:
105 result = pytester.runpytest("--basetemp=.")
106 result.stderr.fnmatch_lines("*basetemp must not be*")
107
108
109 class TestResolveCollectionArgument:
110 @pytest.fixture
111 def invocation_path(self, pytester: Pytester) -> Path:
112 pytester.syspathinsert(pytester.path / "src")
113 pytester.chdir()
114
115 pkg = pytester.path.joinpath("src/pkg")
116 pkg.mkdir(parents=True)
117 pkg.joinpath("__init__.py").touch()
118 pkg.joinpath("test.py").touch()
119 return pytester.path
120
121 def test_file(self, invocation_path: Path) -> None:
122 """File and parts."""
123 assert resolve_collection_argument(
124 invocation_path, "src/pkg/test.py", 0
125 ) == CollectionArgument(
126 path=invocation_path / "src/pkg/test.py",
127 parts=[],
128 parametrization=None,
129 module_name=None,
130 original_index=0,
131 )
132 assert resolve_collection_argument(
133 invocation_path, "src/pkg/test.py::", 10
134 ) == CollectionArgument(
135 path=invocation_path / "src/pkg/test.py",
136 parts=[""],
137 parametrization=None,
138 module_name=None,
139 original_index=10,
140 )
141 assert resolve_collection_argument(
142 invocation_path, "src/pkg/test.py::foo::bar", 20
143 ) == CollectionArgument(
144 path=invocation_path / "src/pkg/test.py",
145 parts=["foo", "bar"],
146 parametrization=None,
147 module_name=None,
148 original_index=20,
149 )
150 assert resolve_collection_argument(
151 invocation_path, "src/pkg/test.py::foo::bar::", 30
152 ) == CollectionArgument(
153 path=invocation_path / "src/pkg/test.py",
154 parts=["foo", "bar", ""],
155 parametrization=None,
156 module_name=None,
157 original_index=30,
158 )
159 assert resolve_collection_argument(
160 invocation_path, "src/pkg/test.py::foo::bar[a,b,c]", 40
161 ) == CollectionArgument(
162 path=invocation_path / "src/pkg/test.py",
163 parts=["foo", "bar"],
164 parametrization="[a,b,c]",
165 module_name=None,
166 original_index=40,
167 )
168
169 def test_dir(self, invocation_path: Path) -> None:
170 """Directory and parts."""
171 assert resolve_collection_argument(
172 invocation_path, "src/pkg", 0
173 ) == CollectionArgument(
174 path=invocation_path / "src/pkg",
175 parts=[],
176 parametrization=None,
177 module_name=None,
178 original_index=0,
179 )
180
181 with pytest.raises(
182 UsageError, match=r"directory argument cannot contain :: selection parts"
183 ):
184 resolve_collection_argument(invocation_path, "src/pkg::", 0)
185
186 with pytest.raises(
187 UsageError, match=r"directory argument cannot contain :: selection parts"
188 ):
189 resolve_collection_argument(invocation_path, "src/pkg::foo::bar", 0)
190
191 @pytest.mark.parametrize("namespace_package", [False, True])
192 def test_pypath(self, namespace_package: bool, invocation_path: Path) -> None:
193 """Dotted name and parts."""
194 if namespace_package:
195 # Namespace package doesn't have to contain __init__py
196 (invocation_path / "src/pkg/__init__.py").unlink()
197
198 assert resolve_collection_argument(
199 invocation_path, "pkg.test", 0, as_pypath=True
200 ) == CollectionArgument(
201 path=invocation_path / "src/pkg/test.py",
202 parts=[],
203 parametrization=None,
204 module_name="pkg.test",
205 original_index=0,
206 )
207 assert resolve_collection_argument(
208 invocation_path, "pkg.test::foo::bar", 0, as_pypath=True
209 ) == CollectionArgument(
210 path=invocation_path / "src/pkg/test.py",
211 parts=["foo", "bar"],
212 parametrization=None,
213 module_name="pkg.test",
214 original_index=0,
215 )
216 assert resolve_collection_argument(
217 invocation_path,
218 "pkg",
219 0,
220 as_pypath=True,
221 consider_namespace_packages=namespace_package,
222 ) == CollectionArgument(
223 path=invocation_path / "src/pkg",
224 parts=[],
225 parametrization=None,
226 module_name="pkg",
227 original_index=0,
228 )
229
230 with pytest.raises(
231 UsageError, match=r"package argument cannot contain :: selection parts"
232 ):
233 resolve_collection_argument(
234 invocation_path,
235 "pkg::foo::bar",
236 0,
237 as_pypath=True,
238 consider_namespace_packages=namespace_package,
239 )
240
241 def test_parametrized_name_with_colons(self, invocation_path: Path) -> None:
242 assert resolve_collection_argument(
243 invocation_path, "src/pkg/test.py::test[a::b]", 0
244 ) == CollectionArgument(
245 path=invocation_path / "src/pkg/test.py",
246 parts=["test"],
247 parametrization="[a::b]",
248 module_name=None,
249 original_index=0,
250 )
251
252 @pytest.mark.parametrize(
253 "arg", ["x.py[a]", "x.py[a]::foo", "x/y.py[a]::foo::bar", "x.py[a]::foo[b]"]
254 )
255 def test_path_parametrization_not_allowed(
256 self, invocation_path: Path, arg: str
257 ) -> None:
258 with pytest.raises(
259 UsageError, match=r"path cannot contain \[\] parametrization"
260 ):
261 resolve_collection_argument(invocation_path, arg, 0)
262
263 def test_does_not_exist(self, invocation_path: Path) -> None:
264 """Given a file/module that does not exist raises UsageError."""
265 with pytest.raises(
266 UsageError, match=re.escape("file or directory not found: foobar")
267 ):
268 resolve_collection_argument(invocation_path, "foobar", 0)
269
270 with pytest.raises(
271 UsageError,
272 match=re.escape(
273 "module or package not found: foobar (missing __init__.py?)"
274 ),
275 ):
276 resolve_collection_argument(invocation_path, "foobar", 0, as_pypath=True)
277
278 def test_absolute_paths_are_resolved_correctly(self, invocation_path: Path) -> None:
279 """Absolute paths resolve back to absolute paths."""
280 full_path = str(invocation_path / "src")
281 assert resolve_collection_argument(
282 invocation_path, full_path, 0
283 ) == CollectionArgument(
284 path=Path(os.path.abspath("src")),
285 parts=[],
286 parametrization=None,
287 module_name=None,
288 original_index=0,
289 )
290
291 # ensure full paths given in the command-line without the drive letter resolve
292 # to the full path correctly (#7628)
293 _drive, full_path_without_drive = os.path.splitdrive(full_path)
294 assert resolve_collection_argument(
295 invocation_path, full_path_without_drive, 0
296 ) == CollectionArgument(
297 path=Path(os.path.abspath("src")),
298 parts=[],
299 parametrization=None,
300 module_name=None,
301 original_index=0,
302 )
303
304
305 def test_module_full_path_without_drive(pytester: Pytester) -> None:
306 """Collect and run test using full path except for the drive letter (#7628).
307
308 Passing a full path without a drive letter would trigger a bug in legacy_path
309 where it would keep the full path without the drive letter around, instead of resolving
310 to the full path, resulting in fixtures node ids not matching against test node ids correctly.
311 """
312 pytester.makepyfile(
313 **{
314 "project/conftest.py": """
315 import pytest
316 @pytest.fixture
317 def fix(): return 1
318 """,
319 }
320 )
321
322 pytester.makepyfile(
323 **{
324 "project/tests/dummy_test.py": """
325 def test(fix):
326 assert fix == 1
327 """
328 }
329 )
330 fn = pytester.path.joinpath("project/tests/dummy_test.py")
331 assert fn.is_file()
332
333 _drive, path = os.path.splitdrive(str(fn))
334
335 result = pytester.runpytest(path, "-v")
336 result.stdout.fnmatch_lines(
337 [
338 os.path.join("project", "tests", "dummy_test.py") + "::test PASSED *",
339 "* 1 passed in *",
340 ]
341 )
342
343
344 def test_very_long_cmdline_arg(pytester: Pytester) -> None:
345 """
346 Regression test for #11394.
347
348 Note: we could not manage to actually reproduce the error with this code, we suspect
349 GitHub runners are configured to support very long paths, however decided to leave
350 the test in place in case this ever regresses in the future.
351 """
352 pytester.makeconftest(
353 """
354 import pytest
355
356 def pytest_addoption(parser):
357 parser.addoption("--long-list", dest="long_list", action="store", default="all", help="List of things")
358
359 @pytest.fixture(scope="module")
360 def specified_feeds(request):
361 list_string = request.config.getoption("--long-list")
362 return list_string.split(',')
363 """
364 )
365 pytester.makepyfile(
366 """
367 def test_foo(specified_feeds):
368 assert len(specified_feeds) == 100_000
369 """
370 )
371 result = pytester.runpytest("--long-list", ",".join(["helloworld"] * 100_000))
372 result.stdout.fnmatch_lines("* 1 passed *")