| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import os |
| 5 |
import subprocess |
| 6 |
import sys |
| 7 |
from types import ModuleType |
| 8 |
|
| 9 |
from _pytest.config import ExitCode |
| 10 |
from _pytest.config import PytestPluginManager |
| 11 |
from _pytest.monkeypatch import MonkeyPatch |
| 12 |
import _pytest.pytester as pytester_mod |
| 13 |
from _pytest.pytester import HookRecorder |
| 14 |
from _pytest.pytester import LineMatcher |
| 15 |
from _pytest.pytester import Pytester |
| 16 |
from _pytest.pytester import SysModulesSnapshot |
| 17 |
from _pytest.pytester import SysPathsSnapshot |
| 18 |
import _pytest.timing |
| 19 |
import pytest |
| 20 |
|
| 21 |
|
| 22 |
def test_make_hook_recorder(pytester: Pytester) -> None: |
| 23 |
item = pytester.getitem("def test_func(): pass") |
| 24 |
recorder = pytester.make_hook_recorder(item.config.pluginmanager) |
| 25 |
assert not recorder.getfailures() |
| 26 |
|
| 27 |
# (The silly condition is to fool mypy that the code below this is reachable) |
| 28 |
if 1 + 1 == 2: |
| 29 |
pytest.xfail("internal reportrecorder tests need refactoring") |
| 30 |
|
| 31 |
class rep: |
| 32 |
excinfo = None |
| 33 |
passed = False |
| 34 |
failed = True |
| 35 |
skipped = False |
| 36 |
when = "call" |
| 37 |
|
| 38 |
recorder.hook.pytest_runtest_logreport(report=rep) # type: ignore[attr-defined] |
| 39 |
failures = recorder.getfailures() |
| 40 |
assert failures == [rep] # type: ignore[comparison-overlap] |
| 41 |
failures = recorder.getfailures() |
| 42 |
assert failures == [rep] # type: ignore[comparison-overlap] |
| 43 |
|
| 44 |
class rep2: |
| 45 |
excinfo = None |
| 46 |
passed = False |
| 47 |
failed = False |
| 48 |
skipped = True |
| 49 |
when = "call" |
| 50 |
|
| 51 |
rep2.passed = False |
| 52 |
rep2.skipped = True |
| 53 |
recorder.hook.pytest_runtest_logreport(report=rep2) # type: ignore[attr-defined] |
| 54 |
|
| 55 |
modcol = pytester.getmodulecol("") |
| 56 |
rep3 = modcol.config.hook.pytest_make_collect_report(collector=modcol) |
| 57 |
rep3.passed = False |
| 58 |
rep3.failed = True |
| 59 |
rep3.skipped = False |
| 60 |
recorder.hook.pytest_collectreport(report=rep3) # type: ignore[attr-defined] |
| 61 |
|
| 62 |
passed, skipped, failed = recorder.listoutcomes() |
| 63 |
assert not passed and skipped and failed |
| 64 |
|
| 65 |
numpassed, numskipped, numfailed = recorder.countoutcomes() |
| 66 |
assert numpassed == 0 |
| 67 |
assert numskipped == 1 |
| 68 |
assert numfailed == 1 |
| 69 |
assert len(recorder.getfailedcollections()) == 1 |
| 70 |
|
| 71 |
recorder.unregister() # type: ignore[attr-defined] |
| 72 |
recorder.clear() |
| 73 |
recorder.hook.pytest_runtest_logreport(report=rep3) # type: ignore[attr-defined] |
| 74 |
with pytest.raises(ValueError): |
| 75 |
recorder.getfailures() |
| 76 |
|
| 77 |
|
| 78 |
def test_parseconfig(pytester: Pytester) -> None: |
| 79 |
config1 = pytester.parseconfig() |
| 80 |
config2 = pytester.parseconfig() |
| 81 |
assert config2 is not config1 |
| 82 |
|
| 83 |
|
| 84 |
def test_pytester_runs_with_plugin(pytester: Pytester) -> None: |
| 85 |
pytester.makepyfile( |
| 86 |
""" |
| 87 |
pytest_plugins = "pytester" |
| 88 |
def test_hello(pytester): |
| 89 |
assert 1 |
| 90 |
""" |
| 91 |
) |
| 92 |
result = pytester.runpytest() |
| 93 |
result.assert_outcomes(passed=1) |
| 94 |
|
| 95 |
|
| 96 |
def test_pytester_with_doctest(pytester: Pytester) -> None: |
| 97 |
"""Check that pytester can be used within doctests. |
| 98 |
|
| 99 |
It used to use `request.function`, which is `None` with doctests.""" |
| 100 |
pytester.makepyfile( |
| 101 |
**{ |
| 102 |
"sub/t-doctest.py": """ |
| 103 |
''' |
| 104 |
>>> import os |
| 105 |
>>> pytester = getfixture("pytester") |
| 106 |
>>> str(pytester.makepyfile("content")).replace(os.sep, '/') |
| 107 |
'.../basetemp/sub.t-doctest0/sub.py' |
| 108 |
''' |
| 109 |
""", |
| 110 |
"sub/__init__.py": "", |
| 111 |
} |
| 112 |
) |
| 113 |
result = pytester.runpytest( |
| 114 |
"-p", "pytester", "--doctest-modules", "sub/t-doctest.py" |
| 115 |
) |
| 116 |
assert result.ret == 0 |
| 117 |
|
| 118 |
|
| 119 |
def test_runresult_assertion_on_xfail(pytester: Pytester) -> None: |
| 120 |
pytester.makepyfile( |
| 121 |
""" |
| 122 |
import pytest |
| 123 |
|
| 124 |
pytest_plugins = "pytester" |
| 125 |
|
| 126 |
@pytest.mark.xfail |
| 127 |
def test_potato(): |
| 128 |
assert False |
| 129 |
""" |
| 130 |
) |
| 131 |
result = pytester.runpytest() |
| 132 |
result.assert_outcomes(xfailed=1) |
| 133 |
assert result.ret == 0 |
| 134 |
|
| 135 |
|
| 136 |
def test_runresult_assertion_on_xpassed(pytester: Pytester) -> None: |
| 137 |
pytester.makepyfile( |
| 138 |
""" |
| 139 |
import pytest |
| 140 |
|
| 141 |
pytest_plugins = "pytester" |
| 142 |
|
| 143 |
@pytest.mark.xfail |
| 144 |
def test_potato(): |
| 145 |
assert True |
| 146 |
""" |
| 147 |
) |
| 148 |
result = pytester.runpytest() |
| 149 |
result.assert_outcomes(xpassed=1) |
| 150 |
assert result.ret == 0 |
| 151 |
|
| 152 |
|
| 153 |
def test_xpassed_with_strict_is_considered_a_failure(pytester: Pytester) -> None: |
| 154 |
pytester.makepyfile( |
| 155 |
""" |
| 156 |
import pytest |
| 157 |
|
| 158 |
pytest_plugins = "pytester" |
| 159 |
|
| 160 |
@pytest.mark.xfail(strict=True) |
| 161 |
def test_potato(): |
| 162 |
assert True |
| 163 |
""" |
| 164 |
) |
| 165 |
result = pytester.runpytest() |
| 166 |
result.assert_outcomes(failed=1) |
| 167 |
assert result.ret != 0 |
| 168 |
|
| 169 |
|
| 170 |
def make_holder(): |
| 171 |
class apiclass: |
| 172 |
def pytest_xyz(self, arg): |
| 173 |
"""X""" |
| 174 |
|
| 175 |
def pytest_xyz_noarg(self): |
| 176 |
"""X""" |
| 177 |
|
| 178 |
apimod = type(os)("api") |
| 179 |
|
| 180 |
def pytest_xyz(arg): |
| 181 |
"""X""" |
| 182 |
|
| 183 |
def pytest_xyz_noarg(): |
| 184 |
"""X""" |
| 185 |
|
| 186 |
apimod.pytest_xyz = pytest_xyz # type: ignore |
| 187 |
apimod.pytest_xyz_noarg = pytest_xyz_noarg # type: ignore |
| 188 |
return apiclass, apimod |
| 189 |
|
| 190 |
|
| 191 |
@pytest.mark.parametrize("holder", make_holder()) |
| 192 |
def test_hookrecorder_basic(holder) -> None: |
| 193 |
pm = PytestPluginManager() |
| 194 |
pm.add_hookspecs(holder) |
| 195 |
rec = HookRecorder(pm, _ispytest=True) |
| 196 |
pm.hook.pytest_xyz(arg=123) |
| 197 |
call = rec.popcall("pytest_xyz") |
| 198 |
assert call.arg == 123 |
| 199 |
assert call._name == "pytest_xyz" |
| 200 |
with pytest.raises(pytest.fail.Exception): |
| 201 |
rec.popcall("abc") |
| 202 |
pm.hook.pytest_xyz_noarg() |
| 203 |
call = rec.popcall("pytest_xyz_noarg") |
| 204 |
assert call._name == "pytest_xyz_noarg" |
| 205 |
|
| 206 |
|
| 207 |
def test_makepyfile_unicode(pytester: Pytester) -> None: |
| 208 |
pytester.makepyfile(chr(0xFFFD)) |
| 209 |
|
| 210 |
|
| 211 |
def test_makepyfile_utf8(pytester: Pytester) -> None: |
| 212 |
"""Ensure makepyfile accepts utf-8 bytes as input (#2738)""" |
| 213 |
utf8_contents = """ |
| 214 |
def setup_function(function): |
| 215 |
mixed_encoding = 'São Paulo' |
| 216 |
""".encode() |
| 217 |
p = pytester.makepyfile(utf8_contents) |
| 218 |
assert "mixed_encoding = 'São Paulo'".encode() in p.read_bytes() |
| 219 |
|
| 220 |
|
| 221 |
class TestInlineRunModulesCleanup: |
| 222 |
def test_inline_run_test_module_not_cleaned_up(self, pytester: Pytester) -> None: |
| 223 |
test_mod = pytester.makepyfile("def test_foo(): assert True") |
| 224 |
result = pytester.inline_run(str(test_mod)) |
| 225 |
assert result.ret == ExitCode.OK |
| 226 |
# rewrite module, now test should fail if module was re-imported |
| 227 |
test_mod.write_text("def test_foo(): assert False", encoding="utf-8") |
| 228 |
result2 = pytester.inline_run(str(test_mod)) |
| 229 |
assert result2.ret == ExitCode.TESTS_FAILED |
| 230 |
|
| 231 |
def spy_factory(self): |
| 232 |
class SysModulesSnapshotSpy: |
| 233 |
instances: list[SysModulesSnapshotSpy] = [] |
| 234 |
|
| 235 |
def __init__(self, preserve=None) -> None: |
| 236 |
SysModulesSnapshotSpy.instances.append(self) |
| 237 |
self._spy_restore_count = 0 |
| 238 |
self._spy_preserve = preserve |
| 239 |
self.__snapshot = SysModulesSnapshot(preserve=preserve) |
| 240 |
|
| 241 |
def restore(self): |
| 242 |
self._spy_restore_count += 1 |
| 243 |
return self.__snapshot.restore() |
| 244 |
|
| 245 |
return SysModulesSnapshotSpy |
| 246 |
|
| 247 |
def test_inline_run_taking_and_restoring_a_sys_modules_snapshot( |
| 248 |
self, pytester: Pytester, monkeypatch: MonkeyPatch |
| 249 |
) -> None: |
| 250 |
spy_factory = self.spy_factory() |
| 251 |
monkeypatch.setattr(pytester_mod, "SysModulesSnapshot", spy_factory) |
| 252 |
pytester.syspathinsert() |
| 253 |
original = dict(sys.modules) |
| 254 |
pytester.makepyfile(import1="# you son of a silly person") |
| 255 |
pytester.makepyfile(import2="# my hovercraft is full of eels") |
| 256 |
test_mod = pytester.makepyfile( |
| 257 |
""" |
| 258 |
import import1 |
| 259 |
def test_foo(): import import2""" |
| 260 |
) |
| 261 |
pytester.inline_run(str(test_mod)) |
| 262 |
assert len(spy_factory.instances) == 1 |
| 263 |
spy = spy_factory.instances[0] |
| 264 |
assert spy._spy_restore_count == 1 |
| 265 |
assert sys.modules == original |
| 266 |
assert all(sys.modules[x] is original[x] for x in sys.modules) |
| 267 |
|
| 268 |
def test_inline_run_sys_modules_snapshot_restore_preserving_modules( |
| 269 |
self, pytester: Pytester, monkeypatch: MonkeyPatch |
| 270 |
) -> None: |
| 271 |
spy_factory = self.spy_factory() |
| 272 |
monkeypatch.setattr(pytester_mod, "SysModulesSnapshot", spy_factory) |
| 273 |
test_mod = pytester.makepyfile("def test_foo(): pass") |
| 274 |
pytester.inline_run(str(test_mod)) |
| 275 |
spy = spy_factory.instances[0] |
| 276 |
assert not spy._spy_preserve("black_knight") |
| 277 |
assert spy._spy_preserve("zope") |
| 278 |
assert spy._spy_preserve("zope.interface") |
| 279 |
assert spy._spy_preserve("zopelicious") |
| 280 |
|
| 281 |
def test_external_test_module_imports_not_cleaned_up( |
| 282 |
self, pytester: Pytester |
| 283 |
) -> None: |
| 284 |
pytester.syspathinsert() |
| 285 |
pytester.makepyfile(imported="data = 'you son of a silly person'") |
| 286 |
import imported |
| 287 |
|
| 288 |
test_mod = pytester.makepyfile( |
| 289 |
""" |
| 290 |
def test_foo(): |
| 291 |
import imported |
| 292 |
imported.data = 42""" |
| 293 |
) |
| 294 |
pytester.inline_run(str(test_mod)) |
| 295 |
assert imported.data == 42 |
| 296 |
|
| 297 |
|
| 298 |
def test_assert_outcomes_after_pytest_error(pytester: Pytester) -> None: |
| 299 |
pytester.makepyfile("def test_foo(): assert True") |
| 300 |
|
| 301 |
result = pytester.runpytest("--unexpected-argument") |
| 302 |
with pytest.raises(ValueError, match="Pytest terminal summary report not found"): |
| 303 |
result.assert_outcomes(passed=0) |
| 304 |
|
| 305 |
|
| 306 |
class TestSysModulesSnapshot: |
| 307 |
key = "my-test-module" |
| 308 |
|
| 309 |
def test_remove_added(self) -> None: |
| 310 |
original = dict(sys.modules) |
| 311 |
assert self.key not in sys.modules |
| 312 |
snapshot = SysModulesSnapshot() |
| 313 |
sys.modules[self.key] = ModuleType("something") |
| 314 |
assert self.key in sys.modules |
| 315 |
snapshot.restore() |
| 316 |
assert sys.modules == original |
| 317 |
|
| 318 |
def test_add_removed(self, monkeypatch: MonkeyPatch) -> None: |
| 319 |
assert self.key not in sys.modules |
| 320 |
monkeypatch.setitem(sys.modules, self.key, ModuleType("something")) |
| 321 |
assert self.key in sys.modules |
| 322 |
original = dict(sys.modules) |
| 323 |
snapshot = SysModulesSnapshot() |
| 324 |
del sys.modules[self.key] |
| 325 |
assert self.key not in sys.modules |
| 326 |
snapshot.restore() |
| 327 |
assert sys.modules == original |
| 328 |
|
| 329 |
def test_restore_reloaded(self, monkeypatch: MonkeyPatch) -> None: |
| 330 |
assert self.key not in sys.modules |
| 331 |
monkeypatch.setitem(sys.modules, self.key, ModuleType("something")) |
| 332 |
assert self.key in sys.modules |
| 333 |
original = dict(sys.modules) |
| 334 |
snapshot = SysModulesSnapshot() |
| 335 |
sys.modules[self.key] = ModuleType("something else") |
| 336 |
snapshot.restore() |
| 337 |
assert sys.modules == original |
| 338 |
|
| 339 |
def test_preserve_modules(self, monkeypatch: MonkeyPatch) -> None: |
| 340 |
key = [self.key + str(i) for i in range(3)] |
| 341 |
assert not any(k in sys.modules for k in key) |
| 342 |
for i, k in enumerate(key): |
| 343 |
mod = ModuleType("something" + str(i)) |
| 344 |
monkeypatch.setitem(sys.modules, k, mod) |
| 345 |
original = dict(sys.modules) |
| 346 |
|
| 347 |
def preserve(name): |
| 348 |
return name in (key[0], key[1], "some-other-key") |
| 349 |
|
| 350 |
snapshot = SysModulesSnapshot(preserve=preserve) |
| 351 |
sys.modules[key[0]] = original[key[0]] = ModuleType("something else0") |
| 352 |
sys.modules[key[1]] = original[key[1]] = ModuleType("something else1") |
| 353 |
sys.modules[key[2]] = ModuleType("something else2") |
| 354 |
snapshot.restore() |
| 355 |
assert sys.modules == original |
| 356 |
|
| 357 |
def test_preserve_container(self, monkeypatch: MonkeyPatch) -> None: |
| 358 |
original = dict(sys.modules) |
| 359 |
assert self.key not in original |
| 360 |
replacement = dict(sys.modules) |
| 361 |
replacement[self.key] = ModuleType("life of brian") |
| 362 |
snapshot = SysModulesSnapshot() |
| 363 |
monkeypatch.setattr(sys, "modules", replacement) |
| 364 |
snapshot.restore() |
| 365 |
assert sys.modules is replacement |
| 366 |
assert sys.modules == original |
| 367 |
|
| 368 |
|
| 369 |
@pytest.mark.parametrize("path_type", ("path", "meta_path")) |
| 370 |
class TestSysPathsSnapshot: |
| 371 |
other_path = {"path": "meta_path", "meta_path": "path"} |
| 372 |
|
| 373 |
@staticmethod |
| 374 |
def path(n: int) -> str: |
| 375 |
return "my-dirty-little-secret-" + str(n) |
| 376 |
|
| 377 |
def test_restore(self, monkeypatch: MonkeyPatch, path_type) -> None: |
| 378 |
other_path_type = self.other_path[path_type] |
| 379 |
for i in range(10): |
| 380 |
assert self.path(i) not in getattr(sys, path_type) |
| 381 |
sys_path = [self.path(i) for i in range(6)] |
| 382 |
monkeypatch.setattr(sys, path_type, sys_path) |
| 383 |
original = list(sys_path) |
| 384 |
original_other = list(getattr(sys, other_path_type)) |
| 385 |
snapshot = SysPathsSnapshot() |
| 386 |
transformation = {"source": (0, 1, 2, 3, 4, 5), "target": (6, 2, 9, 7, 5, 8)} |
| 387 |
assert sys_path == [self.path(x) for x in transformation["source"]] |
| 388 |
sys_path[1] = self.path(6) |
| 389 |
sys_path[3] = self.path(7) |
| 390 |
sys_path.append(self.path(8)) |
| 391 |
del sys_path[4] |
| 392 |
sys_path[3:3] = [self.path(9)] |
| 393 |
del sys_path[0] |
| 394 |
assert sys_path == [self.path(x) for x in transformation["target"]] |
| 395 |
snapshot.restore() |
| 396 |
assert getattr(sys, path_type) is sys_path |
| 397 |
assert getattr(sys, path_type) == original |
| 398 |
assert getattr(sys, other_path_type) == original_other |
| 399 |
|
| 400 |
def test_preserve_container(self, monkeypatch: MonkeyPatch, path_type) -> None: |
| 401 |
other_path_type = self.other_path[path_type] |
| 402 |
original_data = list(getattr(sys, path_type)) |
| 403 |
original_other = getattr(sys, other_path_type) |
| 404 |
original_other_data = list(original_other) |
| 405 |
new: list[object] = [] |
| 406 |
snapshot = SysPathsSnapshot() |
| 407 |
monkeypatch.setattr(sys, path_type, new) |
| 408 |
snapshot.restore() |
| 409 |
assert getattr(sys, path_type) is new |
| 410 |
assert getattr(sys, path_type) == original_data |
| 411 |
assert getattr(sys, other_path_type) is original_other |
| 412 |
assert getattr(sys, other_path_type) == original_other_data |
| 413 |
|
| 414 |
|
| 415 |
def test_pytester_subprocess(pytester: Pytester) -> None: |
| 416 |
testfile = pytester.makepyfile("def test_one(): pass") |
| 417 |
assert pytester.runpytest_subprocess(testfile).ret == 0 |
| 418 |
|
| 419 |
|
| 420 |
def test_pytester_subprocess_via_runpytest_arg(pytester: Pytester) -> None: |
| 421 |
testfile = pytester.makepyfile( |
| 422 |
""" |
| 423 |
def test_pytester_subprocess(pytester): |
| 424 |
import os |
| 425 |
testfile = pytester.makepyfile( |
| 426 |
\""" |
| 427 |
import os |
| 428 |
def test_one(): |
| 429 |
assert {} != os.getpid() |
| 430 |
\""".format(os.getpid()) |
| 431 |
) |
| 432 |
assert pytester.runpytest(testfile).ret == 0 |
| 433 |
""" |
| 434 |
) |
| 435 |
result = pytester.runpytest_inprocess( |
| 436 |
"-p", "pytester", "--runpytest", "subprocess", testfile |
| 437 |
) |
| 438 |
assert result.ret == 0 |
| 439 |
|
| 440 |
|
| 441 |
def test_unicode_args(pytester: Pytester) -> None: |
| 442 |
result = pytester.runpytest("-k", "אבג") |
| 443 |
assert result.ret == ExitCode.NO_TESTS_COLLECTED |
| 444 |
|
| 445 |
|
| 446 |
def test_pytester_run_no_timeout(pytester: Pytester) -> None: |
| 447 |
testfile = pytester.makepyfile("def test_no_timeout(): pass") |
| 448 |
assert pytester.runpytest_subprocess(testfile).ret == ExitCode.OK |
| 449 |
|
| 450 |
|
| 451 |
def test_pytester_run_with_timeout(pytester: Pytester) -> None: |
| 452 |
testfile = pytester.makepyfile("def test_no_timeout(): pass") |
| 453 |
|
| 454 |
timeout = 120 |
| 455 |
|
| 456 |
instant = _pytest.timing.Instant() |
| 457 |
result = pytester.runpytest_subprocess(testfile, timeout=timeout) |
| 458 |
duration = instant.elapsed() |
| 459 |
|
| 460 |
assert result.ret == ExitCode.OK |
| 461 |
assert duration.seconds < timeout |
| 462 |
|
| 463 |
|
| 464 |
def test_pytester_run_timeout_expires(pytester: Pytester) -> None: |
| 465 |
testfile = pytester.makepyfile( |
| 466 |
""" |
| 467 |
import time |
| 468 |
|
| 469 |
def test_timeout(): |
| 470 |
time.sleep(10)""" |
| 471 |
) |
| 472 |
with pytest.raises(pytester.TimeoutExpired): |
| 473 |
pytester.runpytest_subprocess(testfile, timeout=1) |
| 474 |
|
| 475 |
|
| 476 |
def test_linematcher_with_nonlist() -> None: |
| 477 |
"""Test LineMatcher with regard to passing in a set (accidentally).""" |
| 478 |
from _pytest._code.source import Source |
| 479 |
|
| 480 |
lm = LineMatcher([]) |
| 481 |
with pytest.raises(TypeError, match="invalid type for lines2: set"): |
| 482 |
lm.fnmatch_lines(set()) # type: ignore[arg-type] |
| 483 |
with pytest.raises(TypeError, match="invalid type for lines2: dict"): |
| 484 |
lm.fnmatch_lines({}) # type: ignore[arg-type] |
| 485 |
with pytest.raises(TypeError, match="invalid type for lines2: set"): |
| 486 |
lm.re_match_lines(set()) # type: ignore[arg-type] |
| 487 |
with pytest.raises(TypeError, match="invalid type for lines2: dict"): |
| 488 |
lm.re_match_lines({}) # type: ignore[arg-type] |
| 489 |
with pytest.raises(TypeError, match="invalid type for lines2: Source"): |
| 490 |
lm.fnmatch_lines(Source()) # type: ignore[arg-type] |
| 491 |
lm.fnmatch_lines([]) |
| 492 |
lm.fnmatch_lines(()) |
| 493 |
lm.fnmatch_lines("") |
| 494 |
assert lm._getlines({}) == {} # type: ignore[arg-type,comparison-overlap] |
| 495 |
assert lm._getlines(set()) == set() # type: ignore[arg-type,comparison-overlap] |
| 496 |
assert lm._getlines(Source()) == [] |
| 497 |
assert lm._getlines(Source("pass\npass")) == ["pass", "pass"] |
| 498 |
|
| 499 |
|
| 500 |
def test_linematcher_match_failure() -> None: |
| 501 |
lm = LineMatcher(["foo", "foo", "bar"]) |
| 502 |
with pytest.raises(pytest.fail.Exception) as e: |
| 503 |
lm.fnmatch_lines(["foo", "f*", "baz"]) |
| 504 |
assert e.value.msg is not None |
| 505 |
assert e.value.msg.splitlines() == [ |
| 506 |
"exact match: 'foo'", |
| 507 |
"fnmatch: 'f*'", |
| 508 |
" with: 'foo'", |
| 509 |
"nomatch: 'baz'", |
| 510 |
" and: 'bar'", |
| 511 |
"remains unmatched: 'baz'", |
| 512 |
] |
| 513 |
|
| 514 |
lm = LineMatcher(["foo", "foo", "bar"]) |
| 515 |
with pytest.raises(pytest.fail.Exception) as e: |
| 516 |
lm.re_match_lines(["foo", "^f.*", "baz"]) |
| 517 |
assert e.value.msg is not None |
| 518 |
assert e.value.msg.splitlines() == [ |
| 519 |
"exact match: 'foo'", |
| 520 |
"re.match: '^f.*'", |
| 521 |
" with: 'foo'", |
| 522 |
" nomatch: 'baz'", |
| 523 |
" and: 'bar'", |
| 524 |
"remains unmatched: 'baz'", |
| 525 |
] |
| 526 |
|
| 527 |
|
| 528 |
def test_linematcher_consecutive() -> None: |
| 529 |
lm = LineMatcher(["1", "", "2"]) |
| 530 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 531 |
lm.fnmatch_lines(["1", "2"], consecutive=True) |
| 532 |
assert str(excinfo.value).splitlines() == [ |
| 533 |
"exact match: '1'", |
| 534 |
"no consecutive match: '2'", |
| 535 |
" with: ''", |
| 536 |
] |
| 537 |
|
| 538 |
lm.re_match_lines(["1", r"\d?", "2"], consecutive=True) |
| 539 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 540 |
lm.re_match_lines(["1", r"\d", "2"], consecutive=True) |
| 541 |
assert str(excinfo.value).splitlines() == [ |
| 542 |
"exact match: '1'", |
| 543 |
r"no consecutive match: '\\d'", |
| 544 |
" with: ''", |
| 545 |
] |
| 546 |
|
| 547 |
|
| 548 |
@pytest.mark.parametrize("function", ["no_fnmatch_line", "no_re_match_line"]) |
| 549 |
def test_linematcher_no_matching(function: str) -> None: |
| 550 |
if function == "no_fnmatch_line": |
| 551 |
good_pattern = "*.py OK*" |
| 552 |
bad_pattern = "*X.py OK*" |
| 553 |
else: |
| 554 |
assert function == "no_re_match_line" |
| 555 |
good_pattern = r".*py OK" |
| 556 |
bad_pattern = r".*Xpy OK" |
| 557 |
|
| 558 |
lm = LineMatcher( |
| 559 |
[ |
| 560 |
"cachedir: .pytest_cache", |
| 561 |
"collecting ... collected 1 item", |
| 562 |
"", |
| 563 |
"show_fixtures_per_test.py OK", |
| 564 |
"=== elapsed 1s ===", |
| 565 |
] |
| 566 |
) |
| 567 |
|
| 568 |
# check the function twice to ensure we don't accumulate the internal buffer |
| 569 |
for i in range(2): |
| 570 |
with pytest.raises(pytest.fail.Exception) as e: |
| 571 |
func = getattr(lm, function) |
| 572 |
func(good_pattern) |
| 573 |
obtained = str(e.value).splitlines() |
| 574 |
if function == "no_fnmatch_line": |
| 575 |
assert obtained == [ |
| 576 |
f"nomatch: '{good_pattern}'", |
| 577 |
" and: 'cachedir: .pytest_cache'", |
| 578 |
" and: 'collecting ... collected 1 item'", |
| 579 |
" and: ''", |
| 580 |
f"fnmatch: '{good_pattern}'", |
| 581 |
" with: 'show_fixtures_per_test.py OK'", |
| 582 |
] |
| 583 |
else: |
| 584 |
assert obtained == [ |
| 585 |
f" nomatch: '{good_pattern}'", |
| 586 |
" and: 'cachedir: .pytest_cache'", |
| 587 |
" and: 'collecting ... collected 1 item'", |
| 588 |
" and: ''", |
| 589 |
f"re.match: '{good_pattern}'", |
| 590 |
" with: 'show_fixtures_per_test.py OK'", |
| 591 |
] |
| 592 |
|
| 593 |
func = getattr(lm, function) |
| 594 |
func(bad_pattern) # bad pattern does not match any line: passes |
| 595 |
|
| 596 |
|
| 597 |
def test_linematcher_no_matching_after_match() -> None: |
| 598 |
lm = LineMatcher(["1", "2", "3"]) |
| 599 |
lm.fnmatch_lines(["1", "3"]) |
| 600 |
with pytest.raises(pytest.fail.Exception) as e: |
| 601 |
lm.no_fnmatch_line("*") |
| 602 |
assert str(e.value).splitlines() == ["fnmatch: '*'", " with: '1'"] |
| 603 |
|
| 604 |
|
| 605 |
def test_linematcher_string_api() -> None: |
| 606 |
lm = LineMatcher(["foo", "bar"]) |
| 607 |
assert str(lm) == "foo\nbar" |
| 608 |
|
| 609 |
|
| 610 |
def test_pytest_addopts_before_pytester(request, monkeypatch: MonkeyPatch) -> None: |
| 611 |
monkeypatch.setenv("PYTEST_ADDOPTS", "--orig-unused") |
| 612 |
_: Pytester = request.getfixturevalue("pytester") |
| 613 |
assert "PYTEST_ADDOPTS" not in os.environ |
| 614 |
|
| 615 |
|
| 616 |
def test_run_stdin(pytester: Pytester) -> None: |
| 617 |
with pytest.raises(pytester.TimeoutExpired): |
| 618 |
pytester.run( |
| 619 |
sys.executable, |
| 620 |
"-c", |
| 621 |
"import sys, time; time.sleep(1); print(sys.stdin.read())", |
| 622 |
stdin=subprocess.PIPE, |
| 623 |
timeout=0.1, |
| 624 |
) |
| 625 |
|
| 626 |
with pytest.raises(pytester.TimeoutExpired): |
| 627 |
result = pytester.run( |
| 628 |
sys.executable, |
| 629 |
"-c", |
| 630 |
"import sys, time; time.sleep(1); print(sys.stdin.read())", |
| 631 |
stdin=b"input\n2ndline", |
| 632 |
timeout=0.1, |
| 633 |
) |
| 634 |
|
| 635 |
result = pytester.run( |
| 636 |
sys.executable, |
| 637 |
"-c", |
| 638 |
"import sys; print(sys.stdin.read())", |
| 639 |
stdin=b"input\n2ndline", |
| 640 |
) |
| 641 |
assert result.stdout.lines == ["input", "2ndline"] |
| 642 |
assert result.stderr.str() == "" |
| 643 |
assert result.ret == 0 |
| 644 |
|
| 645 |
|
| 646 |
def test_popen_stdin_pipe(pytester: Pytester) -> None: |
| 647 |
proc = pytester.popen( |
| 648 |
[sys.executable, "-c", "import sys; print(sys.stdin.read())"], |
| 649 |
stdout=subprocess.PIPE, |
| 650 |
stderr=subprocess.PIPE, |
| 651 |
stdin=subprocess.PIPE, |
| 652 |
) |
| 653 |
stdin = b"input\n2ndline" |
| 654 |
stdout, stderr = proc.communicate(input=stdin) |
| 655 |
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"] |
| 656 |
assert stderr == b"" |
| 657 |
assert proc.returncode == 0 |
| 658 |
|
| 659 |
|
| 660 |
def test_popen_stdin_bytes(pytester: Pytester) -> None: |
| 661 |
proc = pytester.popen( |
| 662 |
[sys.executable, "-c", "import sys; print(sys.stdin.read())"], |
| 663 |
stdout=subprocess.PIPE, |
| 664 |
stderr=subprocess.PIPE, |
| 665 |
stdin=b"input\n2ndline", |
| 666 |
) |
| 667 |
stdout, stderr = proc.communicate() |
| 668 |
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"] |
| 669 |
assert stderr == b"" |
| 670 |
assert proc.returncode == 0 |
| 671 |
|
| 672 |
|
| 673 |
def test_popen_default_stdin_stderr_and_stdin_None(pytester: Pytester) -> None: |
| 674 |
# stdout, stderr default to pipes, |
| 675 |
# stdin can be None to not close the pipe, avoiding |
| 676 |
# "ValueError: flush of closed file" with `communicate()`. |
| 677 |
# |
| 678 |
# Wraps the test to make it not hang when run with "-s". |
| 679 |
p1 = pytester.makepyfile( |
| 680 |
''' |
| 681 |
import sys |
| 682 |
|
| 683 |
def test_inner(pytester): |
| 684 |
p1 = pytester.makepyfile( |
| 685 |
""" |
| 686 |
import sys |
| 687 |
print(sys.stdin.read()) # empty |
| 688 |
print('stdout') |
| 689 |
sys.stderr.write('stderr') |
| 690 |
""" |
| 691 |
) |
| 692 |
proc = pytester.popen([sys.executable, str(p1)], stdin=None) |
| 693 |
stdout, stderr = proc.communicate(b"ignored") |
| 694 |
assert stdout.splitlines() == [b"", b"stdout"] |
| 695 |
assert stderr.splitlines() == [b"stderr"] |
| 696 |
assert proc.returncode == 0 |
| 697 |
''' |
| 698 |
) |
| 699 |
result = pytester.runpytest("-p", "pytester", str(p1)) |
| 700 |
assert result.ret == 0 |
| 701 |
|
| 702 |
|
| 703 |
def test_spawn_uses_tmphome(pytester: Pytester) -> None: |
| 704 |
tmphome = str(pytester.path) |
| 705 |
assert os.environ.get("HOME") == tmphome |
| 706 |
|
| 707 |
pytester._monkeypatch.setenv("CUSTOMENV", "42") |
| 708 |
|
| 709 |
p1 = pytester.makepyfile( |
| 710 |
f""" |
| 711 |
import os |
| 712 |
|
| 713 |
def test(): |
| 714 |
assert os.environ["HOME"] == {tmphome!r} |
| 715 |
assert os.environ["CUSTOMENV"] == "42" |
| 716 |
""" |
| 717 |
) |
| 718 |
child = pytester.spawn_pytest(str(p1)) |
| 719 |
out = child.read() |
| 720 |
assert child.wait() == 0, out.decode("utf8") |
| 721 |
|
| 722 |
|
| 723 |
def test_run_result_repr() -> None: |
| 724 |
outlines = ["some", "normal", "output"] |
| 725 |
errlines = ["some", "nasty", "errors", "happened"] |
| 726 |
|
| 727 |
# known exit code |
| 728 |
r = pytester_mod.RunResult(1, outlines, errlines, duration=0.5) |
| 729 |
assert repr(r) == ( |
| 730 |
f"<RunResult ret={pytest.ExitCode.TESTS_FAILED!s} len(stdout.lines)=3" |
| 731 |
" len(stderr.lines)=4 duration=0.50s>" |
| 732 |
) |
| 733 |
|
| 734 |
# unknown exit code: just the number |
| 735 |
r = pytester_mod.RunResult(99, outlines, errlines, duration=0.5) |
| 736 |
assert ( |
| 737 |
repr(r) == "<RunResult ret=99 len(stdout.lines)=3" |
| 738 |
" len(stderr.lines)=4 duration=0.50s>" |
| 739 |
) |
| 740 |
|
| 741 |
|
| 742 |
def test_pytester_outcomes_with_multiple_errors(pytester: Pytester) -> None: |
| 743 |
p1 = pytester.makepyfile( |
| 744 |
""" |
| 745 |
import pytest |
| 746 |
|
| 747 |
@pytest.fixture |
| 748 |
def bad_fixture(): |
| 749 |
raise Exception("bad") |
| 750 |
|
| 751 |
def test_error1(bad_fixture): |
| 752 |
pass |
| 753 |
|
| 754 |
def test_error2(bad_fixture): |
| 755 |
pass |
| 756 |
""" |
| 757 |
) |
| 758 |
result = pytester.runpytest(str(p1)) |
| 759 |
result.assert_outcomes(errors=2) |
| 760 |
|
| 761 |
assert result.parseoutcomes() == {"errors": 2} |
| 762 |
|
| 763 |
|
| 764 |
def test_parse_summary_line_always_plural() -> None: |
| 765 |
"""Parsing summaries always returns plural nouns (#6505)""" |
| 766 |
lines = [ |
| 767 |
"some output 1", |
| 768 |
"some output 2", |
| 769 |
"======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====", |
| 770 |
"done.", |
| 771 |
] |
| 772 |
assert pytester_mod.RunResult.parse_summary_nouns(lines) == { |
| 773 |
"errors": 1, |
| 774 |
"failed": 1, |
| 775 |
"passed": 1, |
| 776 |
"warnings": 1, |
| 777 |
} |
| 778 |
|
| 779 |
lines = [ |
| 780 |
"some output 1", |
| 781 |
"some output 2", |
| 782 |
"======= 1 failed, 1 passed, 2 warnings, 2 errors in 0.13s ====", |
| 783 |
"done.", |
| 784 |
] |
| 785 |
assert pytester_mod.RunResult.parse_summary_nouns(lines) == { |
| 786 |
"errors": 2, |
| 787 |
"failed": 1, |
| 788 |
"passed": 1, |
| 789 |
"warnings": 2, |
| 790 |
} |
| 791 |
|
| 792 |
|
| 793 |
def test_makefile_joins_absolute_path(pytester: Pytester) -> None: |
| 794 |
absfile = pytester.path / "absfile" |
| 795 |
p1 = pytester.makepyfile(**{str(absfile): ""}) |
| 796 |
assert str(p1) == str(pytester.path / "absfile.py") |
| 797 |
|
| 798 |
|
| 799 |
def test_pytester_makefile_dot_prefixes_extension_with_warning( |
| 800 |
pytester: Pytester, |
| 801 |
) -> None: |
| 802 |
with pytest.raises( |
| 803 |
ValueError, |
| 804 |
match=r"pytester\.makefile expects a file extension, try \.foo\.bar instead of foo\.bar", |
| 805 |
): |
| 806 |
pytester.makefile("foo.bar", "") |
| 807 |
|
| 808 |
|
| 809 |
@pytest.mark.filterwarnings("default") |
| 810 |
def test_pytester_assert_outcomes_warnings(pytester: Pytester) -> None: |
| 811 |
pytester.makepyfile( |
| 812 |
""" |
| 813 |
import warnings |
| 814 |
|
| 815 |
def test_with_warning(): |
| 816 |
warnings.warn(UserWarning("some custom warning")) |
| 817 |
""" |
| 818 |
) |
| 819 |
result = pytester.runpytest() |
| 820 |
result.assert_outcomes(passed=1, warnings=1) |
| 821 |
# If warnings is not passed, it is not checked at all. |
| 822 |
result.assert_outcomes(passed=1) |
| 823 |
|
| 824 |
|
| 825 |
def test_pytester_outcomes_deselected(pytester: Pytester) -> None: |
| 826 |
pytester.makepyfile( |
| 827 |
""" |
| 828 |
def test_one(): |
| 829 |
pass |
| 830 |
|
| 831 |
def test_two(): |
| 832 |
pass |
| 833 |
""" |
| 834 |
) |
| 835 |
result = pytester.runpytest("-k", "test_one") |
| 836 |
result.assert_outcomes(passed=1, deselected=1) |
| 837 |
# If deselected is not passed, it is not checked at all. |
| 838 |
result.assert_outcomes(passed=1) |
| 839 |
|
| 840 |
|
| 841 |
def test_pytester_subprocess_with_string_plugins(pytester: Pytester) -> None: |
| 842 |
"""Test that pytester.runpytest_subprocess is OK with named (string) |
| 843 |
`.plugins`.""" |
| 844 |
pytester.plugins = ["pytester"] |
| 845 |
|
| 846 |
result = pytester.runpytest_subprocess() |
| 847 |
assert result.ret == ExitCode.NO_TESTS_COLLECTED |
| 848 |
|
| 849 |
|
| 850 |
def test_pytester_subprocess_with_non_string_plugins(pytester: Pytester) -> None: |
| 851 |
"""Test that pytester.runpytest_subprocess fails with a proper error given |
| 852 |
non-string `.plugins`.""" |
| 853 |
|
| 854 |
class MyPlugin: |
| 855 |
pass |
| 856 |
|
| 857 |
pytester.plugins = [MyPlugin()] |
| 858 |
|
| 859 |
with pytest.raises(ValueError, match="plugins as objects is not supported"): |
| 860 |
pytester.runpytest_subprocess() |