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