Skip to content

Commit 8eef8c6

Browse files
authored
tests: Migrate to pytester - incremental update (#8145)
1 parent cb8142b commit 8eef8c6

11 files changed

+801
-703
lines changed

testing/code/test_excinfo.py

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import queue
66
import sys
77
import textwrap
8+
from pathlib import Path
89
from typing import Any
910
from typing import Dict
1011
from typing import Tuple
@@ -19,7 +20,10 @@
1920
from _pytest._code.code import ExceptionInfo
2021
from _pytest._code.code import FormattedExcinfo
2122
from _pytest._io import TerminalWriter
23+
from _pytest.pathlib import import_path
2224
from _pytest.pytester import LineMatcher
25+
from _pytest.pytester import Pytester
26+
2327

2428
if TYPE_CHECKING:
2529
from _pytest._code.code import _TracebackStyle
@@ -155,10 +159,10 @@ def test_traceback_cut(self):
155159
newtraceback = traceback.cut(path=path, lineno=firstlineno + 2)
156160
assert len(newtraceback) == 1
157161

158-
def test_traceback_cut_excludepath(self, testdir):
159-
p = testdir.makepyfile("def f(): raise ValueError")
162+
def test_traceback_cut_excludepath(self, pytester: Pytester) -> None:
163+
p = pytester.makepyfile("def f(): raise ValueError")
160164
with pytest.raises(ValueError) as excinfo:
161-
p.pyimport().f()
165+
import_path(p).f() # type: ignore[attr-defined]
162166
basedir = py.path.local(pytest.__file__).dirpath()
163167
newtraceback = excinfo.traceback.cut(excludepath=basedir)
164168
for x in newtraceback:
@@ -406,8 +410,8 @@ def test_match_succeeds():
406410
excinfo.match(r".*zero.*")
407411

408412

409-
def test_match_raises_error(testdir):
410-
testdir.makepyfile(
413+
def test_match_raises_error(pytester: Pytester) -> None:
414+
pytester.makepyfile(
411415
"""
412416
import pytest
413417
def test_division_zero():
@@ -416,14 +420,14 @@ def test_division_zero():
416420
excinfo.match(r'[123]+')
417421
"""
418422
)
419-
result = testdir.runpytest()
423+
result = pytester.runpytest()
420424
assert result.ret != 0
421425

422426
exc_msg = "Regex pattern '[[]123[]]+' does not match 'division by zero'."
423427
result.stdout.fnmatch_lines([f"E * AssertionError: {exc_msg}"])
424428
result.stdout.no_fnmatch_line("*__tracebackhide__ = True*")
425429

426-
result = testdir.runpytest("--fulltrace")
430+
result = pytester.runpytest("--fulltrace")
427431
assert result.ret != 0
428432
result.stdout.fnmatch_lines(
429433
["*__tracebackhide__ = True*", f"E * AssertionError: {exc_msg}"]
@@ -432,15 +436,14 @@ def test_division_zero():
432436

433437
class TestFormattedExcinfo:
434438
@pytest.fixture
435-
def importasmod(self, request, _sys_snapshot):
439+
def importasmod(self, tmp_path: Path, _sys_snapshot):
436440
def importasmod(source):
437441
source = textwrap.dedent(source)
438-
tmpdir = request.getfixturevalue("tmpdir")
439-
modpath = tmpdir.join("mod.py")
440-
tmpdir.ensure("__init__.py")
441-
modpath.write(source)
442+
modpath = tmp_path.joinpath("mod.py")
443+
tmp_path.joinpath("__init__.py").touch()
444+
modpath.write_text(source)
442445
importlib.invalidate_caches()
443-
return modpath.pyimport()
446+
return import_path(modpath)
444447

445448
return importasmod
446449

@@ -682,7 +685,7 @@ def entry():
682685
p = FormattedExcinfo(style="short")
683686
reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
684687
lines = reprtb.lines
685-
basename = py.path.local(mod.__file__).basename
688+
basename = Path(mod.__file__).name
686689
assert lines[0] == " func1()"
687690
assert reprtb.reprfileloc is not None
688691
assert basename in str(reprtb.reprfileloc.path)
@@ -948,7 +951,9 @@ def f():
948951
assert line.endswith("mod.py")
949952
assert tw_mock.lines[12] == ":3: ValueError"
950953

951-
def test_toterminal_long_missing_source(self, importasmod, tmpdir, tw_mock):
954+
def test_toterminal_long_missing_source(
955+
self, importasmod, tmp_path: Path, tw_mock
956+
) -> None:
952957
mod = importasmod(
953958
"""
954959
def g(x):
@@ -958,7 +963,7 @@ def f():
958963
"""
959964
)
960965
excinfo = pytest.raises(ValueError, mod.f)
961-
tmpdir.join("mod.py").remove()
966+
tmp_path.joinpath("mod.py").unlink()
962967
excinfo.traceback = excinfo.traceback.filter()
963968
repr = excinfo.getrepr()
964969
repr.toterminal(tw_mock)
@@ -978,7 +983,9 @@ def f():
978983
assert line.endswith("mod.py")
979984
assert tw_mock.lines[10] == ":3: ValueError"
980985

981-
def test_toterminal_long_incomplete_source(self, importasmod, tmpdir, tw_mock):
986+
def test_toterminal_long_incomplete_source(
987+
self, importasmod, tmp_path: Path, tw_mock
988+
) -> None:
982989
mod = importasmod(
983990
"""
984991
def g(x):
@@ -988,7 +995,7 @@ def f():
988995
"""
989996
)
990997
excinfo = pytest.raises(ValueError, mod.f)
991-
tmpdir.join("mod.py").write("asdf")
998+
tmp_path.joinpath("mod.py").write_text("asdf")
992999
excinfo.traceback = excinfo.traceback.filter()
9931000
repr = excinfo.getrepr()
9941001
repr.toterminal(tw_mock)
@@ -1374,16 +1381,18 @@ def test_repr_traceback_with_unicode(style, encoding):
13741381
assert repr_traceback is not None
13751382

13761383

1377-
def test_cwd_deleted(testdir):
1378-
testdir.makepyfile(
1384+
def test_cwd_deleted(pytester: Pytester) -> None:
1385+
pytester.makepyfile(
13791386
"""
1380-
def test(tmpdir):
1381-
tmpdir.chdir()
1382-
tmpdir.remove()
1387+
import os
1388+
1389+
def test(tmp_path):
1390+
os.chdir(tmp_path)
1391+
tmp_path.unlink()
13831392
assert False
13841393
"""
13851394
)
1386-
result = testdir.runpytest()
1395+
result = pytester.runpytest()
13871396
result.stdout.fnmatch_lines(["* 1 failed in *"])
13881397
result.stdout.no_fnmatch_line("*INTERNALERROR*")
13891398
result.stderr.no_fnmatch_line("*INTERNALERROR*")

testing/examples/test_issue519.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1-
def test_510(testdir):
2-
testdir.copy_example("issue_519.py")
3-
testdir.runpytest("issue_519.py")
1+
from _pytest.pytester import Pytester
2+
3+
4+
def test_510(pytester: Pytester) -> None:
5+
pytester.copy_example("issue_519.py")
6+
pytester.runpytest("issue_519.py")

testing/io/test_terminalwriter.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44
import shutil
55
import sys
6+
from pathlib import Path
67
from typing import Generator
78
from unittest import mock
89

@@ -64,10 +65,10 @@ def test_terminalwriter_not_unicode() -> None:
6465
class TestTerminalWriter:
6566
@pytest.fixture(params=["path", "stringio"])
6667
def tw(
67-
self, request, tmpdir
68+
self, request, tmp_path: Path
6869
) -> Generator[terminalwriter.TerminalWriter, None, None]:
6970
if request.param == "path":
70-
p = tmpdir.join("tmpfile")
71+
p = tmp_path.joinpath("tmpfile")
7172
f = open(str(p), "w+", encoding="utf8")
7273
tw = terminalwriter.TerminalWriter(f)
7374

testing/logging/test_fixture.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22

33
import pytest
44
from _pytest.logging import caplog_records_key
5-
from _pytest.pytester import Testdir
5+
from _pytest.pytester import Pytester
66

77
logger = logging.getLogger(__name__)
88
sublogger = logging.getLogger(__name__ + ".baz")
99

1010

11-
def test_fixture_help(testdir):
12-
result = testdir.runpytest("--fixtures")
11+
def test_fixture_help(pytester: Pytester) -> None:
12+
result = pytester.runpytest("--fixtures")
1313
result.stdout.fnmatch_lines(["*caplog*"])
1414

1515

@@ -28,12 +28,12 @@ def test_change_level(caplog):
2828
assert "CRITICAL" in caplog.text
2929

3030

31-
def test_change_level_undo(testdir: Testdir) -> None:
31+
def test_change_level_undo(pytester: Pytester) -> None:
3232
"""Ensure that 'set_level' is undone after the end of the test.
3333
3434
Tests the logging output themselves (affacted both by logger and handler levels).
3535
"""
36-
testdir.makepyfile(
36+
pytester.makepyfile(
3737
"""
3838
import logging
3939
@@ -49,17 +49,17 @@ def test2(caplog):
4949
assert 0
5050
"""
5151
)
52-
result = testdir.runpytest()
52+
result = pytester.runpytest()
5353
result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
5454
result.stdout.no_fnmatch_line("*log from test2*")
5555

5656

57-
def test_change_level_undos_handler_level(testdir: Testdir) -> None:
57+
def test_change_level_undos_handler_level(pytester: Pytester) -> None:
5858
"""Ensure that 'set_level' is undone after the end of the test (handler).
5959
6060
Issue #7569. Tests the handler level specifically.
6161
"""
62-
testdir.makepyfile(
62+
pytester.makepyfile(
6363
"""
6464
import logging
6565
@@ -78,7 +78,7 @@ def test3(caplog):
7878
assert caplog.handler.level == 43
7979
"""
8080
)
81-
result = testdir.runpytest()
81+
result = pytester.runpytest()
8282
result.assert_outcomes(passed=3)
8383

8484

@@ -172,8 +172,8 @@ def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardow
172172
assert set(caplog._item._store[caplog_records_key]) == {"setup", "call"}
173173

174174

175-
def test_ini_controls_global_log_level(testdir):
176-
testdir.makepyfile(
175+
def test_ini_controls_global_log_level(pytester: Pytester) -> None:
176+
pytester.makepyfile(
177177
"""
178178
import pytest
179179
import logging
@@ -187,20 +187,20 @@ def test_log_level_override(request, caplog):
187187
assert 'ERROR' in caplog.text
188188
"""
189189
)
190-
testdir.makeini(
190+
pytester.makeini(
191191
"""
192192
[pytest]
193193
log_level=ERROR
194194
"""
195195
)
196196

197-
result = testdir.runpytest()
197+
result = pytester.runpytest()
198198
# make sure that that we get a '0' exit code for the testsuite
199199
assert result.ret == 0
200200

201201

202-
def test_caplog_can_override_global_log_level(testdir):
203-
testdir.makepyfile(
202+
def test_caplog_can_override_global_log_level(pytester: Pytester) -> None:
203+
pytester.makepyfile(
204204
"""
205205
import pytest
206206
import logging
@@ -227,19 +227,19 @@ def test_log_level_override(request, caplog):
227227
assert "message won't be shown" not in caplog.text
228228
"""
229229
)
230-
testdir.makeini(
230+
pytester.makeini(
231231
"""
232232
[pytest]
233233
log_level=WARNING
234234
"""
235235
)
236236

237-
result = testdir.runpytest()
237+
result = pytester.runpytest()
238238
assert result.ret == 0
239239

240240

241-
def test_caplog_captures_despite_exception(testdir):
242-
testdir.makepyfile(
241+
def test_caplog_captures_despite_exception(pytester: Pytester) -> None:
242+
pytester.makepyfile(
243243
"""
244244
import pytest
245245
import logging
@@ -255,26 +255,28 @@ def test_log_level_override(request, caplog):
255255
raise Exception()
256256
"""
257257
)
258-
testdir.makeini(
258+
pytester.makeini(
259259
"""
260260
[pytest]
261261
log_level=WARNING
262262
"""
263263
)
264264

265-
result = testdir.runpytest()
265+
result = pytester.runpytest()
266266
result.stdout.fnmatch_lines(["*ERROR message will be shown*"])
267267
result.stdout.no_fnmatch_line("*DEBUG message won't be shown*")
268268
assert result.ret == 1
269269

270270

271-
def test_log_report_captures_according_to_config_option_upon_failure(testdir):
271+
def test_log_report_captures_according_to_config_option_upon_failure(
272+
pytester: Pytester,
273+
) -> None:
272274
"""Test that upon failure:
273275
(1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised.
274276
(2) The `DEBUG` message does NOT appear in the `Captured log call` report.
275277
(3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`.
276278
"""
277-
testdir.makepyfile(
279+
pytester.makepyfile(
278280
"""
279281
import pytest
280282
import logging
@@ -299,7 +301,7 @@ def test_that_fails(request, caplog):
299301
"""
300302
)
301303

302-
result = testdir.runpytest("--log-level=INFO")
304+
result = pytester.runpytest("--log-level=INFO")
303305
result.stdout.no_fnmatch_line("*Exception: caplog failed to capture DEBUG*")
304306
result.stdout.no_fnmatch_line("*DEBUG log message*")
305307
result.stdout.fnmatch_lines(

0 commit comments

Comments
 (0)