Debian Codegraph @

testing/test_monkeypatch.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 import os
6 from pathlib import Path
7 import re
8 import sys
9 import textwrap
10 import warnings
11
12 from _pytest.monkeypatch import MonkeyPatch
13 from _pytest.pytester import Pytester
14 import pytest
15
16
17 @pytest.fixture
18 def mp() -> Generator[MonkeyPatch]:
19 cwd = os.getcwd()
20 sys_path = list(sys.path)
21 yield MonkeyPatch()
22 sys.path[:] = sys_path
23 os.chdir(cwd)
24
25
26 def test_setattr() -> None:
27 class A:
28 x = 1
29
30 monkeypatch = MonkeyPatch()
31 with pytest.raises(AttributeError):
32 monkeypatch.setattr(A, "notexists", 2)
33 monkeypatch.setattr(A, "y", 2, raising=False)
34 assert A.y == 2 # type: ignore
35 monkeypatch.undo()
36 assert not hasattr(A, "y")
37
38 monkeypatch = MonkeyPatch()
39 monkeypatch.setattr(A, "x", 2)
40 assert A.x == 2
41 monkeypatch.setattr(A, "x", 3)
42 assert A.x == 3
43 monkeypatch.undo()
44 assert A.x == 1
45
46 A.x = 5
47 monkeypatch.undo() # double-undo makes no modification
48 assert A.x == 5
49
50 with pytest.raises(TypeError):
51 monkeypatch.setattr(A, "y") # type: ignore[call-overload]
52
53
54 class TestSetattrWithImportPath:
55 def test_string_expression(self, monkeypatch: MonkeyPatch) -> None:
56 with monkeypatch.context() as mp:
57 mp.setattr("os.path.abspath", lambda x: "hello2")
58 assert os.path.abspath("123") == "hello2"
59
60 def test_string_expression_class(self, monkeypatch: MonkeyPatch) -> None:
61 with monkeypatch.context() as mp:
62 mp.setattr("_pytest.config.Config", 42)
63 import _pytest
64
65 assert _pytest.config.Config == 42 # type: ignore
66
67 def test_unicode_string(self, monkeypatch: MonkeyPatch) -> None:
68 with monkeypatch.context() as mp:
69 mp.setattr("_pytest.config.Config", 42)
70 import _pytest
71
72 assert _pytest.config.Config == 42 # type: ignore
73 mp.delattr("_pytest.config.Config")
74
75 def test_wrong_target(self, monkeypatch: MonkeyPatch) -> None:
76 with pytest.raises(TypeError):
77 monkeypatch.setattr(None, None) # type: ignore[call-overload]
78
79 def test_unknown_import(self, monkeypatch: MonkeyPatch) -> None:
80 with pytest.raises(ImportError):
81 monkeypatch.setattr("unkn123.classx", None)
82
83 def test_unknown_attr(self, monkeypatch: MonkeyPatch) -> None:
84 with pytest.raises(AttributeError):
85 monkeypatch.setattr("os.path.qweqwe", None)
86
87 def test_unknown_attr_non_raising(self, monkeypatch: MonkeyPatch) -> None:
88 # https://github.com/pytest-dev/pytest/issues/746
89 with monkeypatch.context() as mp:
90 mp.setattr("os.path.qweqwe", 42, raising=False)
91 assert os.path.qweqwe == 42 # type: ignore
92
93 def test_setattr_failure_does_not_corrupt_undo(
94 self, monkeypatch: MonkeyPatch
95 ) -> None:
96 """If setattr() raises (e.g. target doesn't support attribute
97 setting), the undo stack should not contain a stale entry that
98 crashes during teardown (#14161)."""
99
100 class Immutable:
101 __slots__ = ()
102
103 target = Immutable()
104 with pytest.raises(AttributeError):
105 monkeypatch.setattr(target, "x", 42, raising=False)
106 # undo() must not raise — no entry should be on the undo stack.
107 monkeypatch.undo()
108
109 def test_delattr(self, monkeypatch: MonkeyPatch) -> None:
110 with monkeypatch.context() as mp:
111 mp.delattr("os.path.abspath")
112 assert not hasattr(os.path, "abspath")
113 mp.undo()
114 assert os.path.abspath # type:ignore[truthy-function]
115
116
117 def test_delattr() -> None:
118 class A:
119 x = 1
120
121 monkeypatch = MonkeyPatch()
122 monkeypatch.delattr(A, "x")
123 assert not hasattr(A, "x")
124 monkeypatch.undo()
125 assert A.x == 1
126
127 monkeypatch = MonkeyPatch()
128 monkeypatch.delattr(A, "x")
129 with pytest.raises(AttributeError):
130 monkeypatch.delattr(A, "y")
131 monkeypatch.delattr(A, "y", raising=False)
132 monkeypatch.setattr(A, "x", 5, raising=False)
133 assert A.x == 5
134 monkeypatch.undo()
135 assert A.x == 1
136
137
138 def test_setitem() -> None:
139 d = {"x": 1}
140 monkeypatch = MonkeyPatch()
141 monkeypatch.setitem(d, "x", 2)
142 monkeypatch.setitem(d, "y", 1700)
143 monkeypatch.setitem(d, "y", 1700)
144 assert d["x"] == 2
145 assert d["y"] == 1700
146 monkeypatch.setitem(d, "x", 3)
147 assert d["x"] == 3
148 monkeypatch.undo()
149 assert d["x"] == 1
150 assert "y" not in d
151 d["x"] = 5
152 monkeypatch.undo()
153 assert d["x"] == 5
154
155
156 def test_setitem_deleted_meanwhile() -> None:
157 d: dict[str, object] = {}
158 monkeypatch = MonkeyPatch()
159 monkeypatch.setitem(d, "x", 2)
160 del d["x"]
161 monkeypatch.undo()
162 assert not d
163
164
165 @pytest.mark.parametrize("before", [True, False])
166 def test_setenv_deleted_meanwhile(before: bool) -> None:
167 key = "qwpeoip123"
168 if before:
169 os.environ[key] = "world"
170 monkeypatch = MonkeyPatch()
171 monkeypatch.setenv(key, "hello")
172 del os.environ[key]
173 monkeypatch.undo()
174 if before:
175 assert os.environ[key] == "world"
176 del os.environ[key]
177 else:
178 assert key not in os.environ
179
180
181 def test_delitem() -> None:
182 d: dict[str, object] = {"x": 1}
183 monkeypatch = MonkeyPatch()
184 monkeypatch.delitem(d, "x")
185 assert "x" not in d
186 monkeypatch.delitem(d, "y", raising=False)
187 with pytest.raises(KeyError):
188 monkeypatch.delitem(d, "y")
189 assert not d
190 monkeypatch.setitem(d, "y", 1700)
191 assert d["y"] == 1700
192 d["hello"] = "world"
193 monkeypatch.setitem(d, "x", 1500)
194 assert d["x"] == 1500
195 monkeypatch.undo()
196 assert d == {"hello": "world", "x": 1}
197
198
199 def test_setenv() -> None:
200 monkeypatch = MonkeyPatch()
201 with pytest.warns(pytest.PytestWarning):
202 monkeypatch.setenv("XYZ123", 2) # type: ignore[arg-type]
203 import os
204
205 assert os.environ["XYZ123"] == "2"
206 monkeypatch.undo()
207 assert "XYZ123" not in os.environ
208
209
210 def test_delenv() -> None:
211 name = "xyz1234"
212 assert name not in os.environ
213 monkeypatch = MonkeyPatch()
214 with pytest.raises(KeyError):
215 monkeypatch.delenv(name, raising=True)
216 monkeypatch.delenv(name, raising=False)
217 monkeypatch.undo()
218 os.environ[name] = "1"
219 try:
220 monkeypatch = MonkeyPatch()
221 monkeypatch.delenv(name)
222 assert name not in os.environ
223 monkeypatch.setenv(name, "3")
224 assert os.environ[name] == "3"
225 monkeypatch.undo()
226 assert os.environ[name] == "1"
227 finally:
228 if name in os.environ:
229 del os.environ[name]
230
231
232 class TestEnvironWarnings:
233 """
234 os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably
235 subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing
236 and raises an error.
237 """
238
239 VAR_NAME = "PYTEST_INTERNAL_MY_VAR"
240
241 def test_setenv_non_str_warning(self, monkeypatch: MonkeyPatch) -> None:
242 value = 2
243 msg = (
244 "Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, "
245 "but got 2 (type: int); converted to str implicitly"
246 )
247 with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):
248 monkeypatch.setenv(str(self.VAR_NAME), value) # type: ignore[arg-type]
249
250
251 def test_setenv_prepend() -> None:
252 import os
253
254 monkeypatch = MonkeyPatch()
255 monkeypatch.setenv("XYZ123", "2", prepend="-")
256 monkeypatch.setenv("XYZ123", "3", prepend="-")
257 assert os.environ["XYZ123"] == "3-2"
258 monkeypatch.undo()
259 assert "XYZ123" not in os.environ
260
261
262 def test_monkeypatch_plugin(pytester: Pytester) -> None:
263 reprec = pytester.inline_runsource(
264 """
265 def test_method(monkeypatch):
266 assert monkeypatch.__class__.__name__ == "MonkeyPatch"
267 """
268 )
269 res = reprec.countoutcomes()
270 assert tuple(res) == (1, 0, 0), res
271
272
273 def test_syspath_prepend(mp: MonkeyPatch) -> None:
274 old = list(sys.path)
275 mp.syspath_prepend("world")
276 mp.syspath_prepend("hello")
277 assert sys.path[0] == "hello"
278 assert sys.path[1] == "world"
279 mp.undo()
280 assert sys.path == old
281 mp.undo()
282 assert sys.path == old
283
284
285 def test_syspath_prepend_double_undo(mp: MonkeyPatch) -> None:
286 old_syspath = sys.path[:]
287 try:
288 mp.syspath_prepend("hello world")
289 mp.undo()
290 sys.path.append("more hello world")
291 mp.undo()
292 assert sys.path[-1] == "more hello world"
293 finally:
294 sys.path[:] = old_syspath
295
296
297 def test_chdir_with_path_local(mp: MonkeyPatch, tmp_path: Path) -> None:
298 mp.chdir(tmp_path)
299 assert os.getcwd() == str(tmp_path)
300
301
302 def test_chdir_with_str(mp: MonkeyPatch, tmp_path: Path) -> None:
303 mp.chdir(str(tmp_path))
304 assert os.getcwd() == str(tmp_path)
305
306
307 def test_chdir_undo(mp: MonkeyPatch, tmp_path: Path) -> None:
308 cwd = os.getcwd()
309 mp.chdir(tmp_path)
310 mp.undo()
311 assert os.getcwd() == cwd
312
313
314 def test_chdir_double_undo(mp: MonkeyPatch, tmp_path: Path) -> None:
315 mp.chdir(str(tmp_path))
316 mp.undo()
317 os.chdir(tmp_path)
318 mp.undo()
319 assert os.getcwd() == str(tmp_path)
320
321
322 def test_issue185_time_breaks(pytester: Pytester) -> None:
323 pytester.makepyfile(
324 """
325 import time
326 def test_m(monkeypatch):
327 def f():
328 raise Exception
329 monkeypatch.setattr(time, "time", f)
330 """
331 )
332 result = pytester.runpytest()
333 result.stdout.fnmatch_lines(
334 """
335 *1 passed*
336 """
337 )
338
339
340 def test_importerror(pytester: Pytester) -> None:
341 p = pytester.mkpydir("package")
342 p.joinpath("a.py").write_text(
343 textwrap.dedent(
344 """\
345 import doesnotexist
346
347 x = 1
348 """
349 ),
350 encoding="utf-8",
351 )
352 pytester.path.joinpath("test_importerror.py").write_text(
353 textwrap.dedent(
354 """\
355 def test_importerror(monkeypatch):
356 monkeypatch.setattr('package.a.x', 2)
357 """
358 ),
359 encoding="utf-8",
360 )
361 result = pytester.runpytest()
362 result.stdout.fnmatch_lines(
363 """
364 *import error in package.a: No module named 'doesnotexist'*
365 """
366 )
367
368
369 class Sample:
370 @staticmethod
371 def hello() -> bool:
372 return True
373
374
375 class SampleInherit(Sample):
376 pass
377
378
379 @pytest.mark.parametrize(
380 "Sample",
381 [Sample, SampleInherit],
382 ids=["new", "new-inherit"],
383 )
384 def test_issue156_undo_staticmethod(Sample: type[Sample]) -> None:
385 monkeypatch = MonkeyPatch()
386
387 monkeypatch.setattr(Sample, "hello", None)
388 assert Sample.hello is None
389
390 monkeypatch.undo() # type: ignore[unreachable]
391 assert Sample.hello()
392
393
394 def test_undo_class_descriptors_delattr() -> None:
395 class SampleParent:
396 @classmethod
397 def hello(_cls):
398 pass
399
400 @staticmethod
401 def world():
402 pass
403
404 class SampleChild(SampleParent):
405 pass
406
407 monkeypatch = MonkeyPatch()
408
409 original_hello = SampleChild.hello
410 original_world = SampleChild.world
411 monkeypatch.delattr(SampleParent, "hello")
412 monkeypatch.delattr(SampleParent, "world")
413 assert getattr(SampleParent, "hello", None) is None
414 assert getattr(SampleParent, "world", None) is None
415
416 monkeypatch.undo()
417 assert original_hello == SampleChild.hello
418 assert original_world == SampleChild.world
419
420
421 def test_issue1338_name_resolving() -> None:
422 pytest.importorskip("requests")
423 monkeypatch = MonkeyPatch()
424 try:
425 monkeypatch.delattr("requests.sessions.Session.request")
426 finally:
427 monkeypatch.undo()
428
429
430 def test_context() -> None:
431 monkeypatch = MonkeyPatch()
432
433 import functools
434 import inspect
435
436 with monkeypatch.context() as m:
437 m.setattr(functools, "partial", 3)
438 assert not inspect.isclass(functools.partial)
439 assert inspect.isclass(functools.partial)
440
441
442 def test_context_classmethod() -> None:
443 class A:
444 x = 1
445
446 with MonkeyPatch.context() as m:
447 m.setattr(A, "x", 2)
448 assert A.x == 2
449 assert A.x == 1
450
451
452 @pytest.mark.filterwarnings(
453 r"ignore:.*\bpkg_resources\b:DeprecationWarning",
454 r"ignore:.*\bpkg_resources\b:UserWarning",
455 )
456 def test_syspath_prepend_with_namespace_packages(
457 pytester: Pytester, monkeypatch: MonkeyPatch
458 ) -> None:
459 # Needs to be in sys.modules.
460 pytest.importorskip("pkg_resources")
461
462 for dirname in "hello", "world":
463 d = pytester.mkdir(dirname)
464 ns = d.joinpath("ns_pkg")
465 ns.mkdir()
466 ns.joinpath("__init__.py").write_text(
467 "__import__('pkg_resources').declare_namespace(__name__)", encoding="utf-8"
468 )
469 lib = ns.joinpath(dirname)
470 lib.mkdir()
471 lib.joinpath("__init__.py").write_text(
472 f"def check(): return {dirname!r}", encoding="utf-8"
473 )
474
475 # First call should not warn - namespace package not registered yet.
476 monkeypatch.syspath_prepend("hello")
477 # This registers ns_pkg as a namespace package.
478 import ns_pkg.hello
479
480 assert ns_pkg.hello.check() == "hello"
481
482 with pytest.raises(ImportError):
483 import ns_pkg.world
484
485 # Prepending should call fixup_namespace_packages.
486 # This call should warn - ns_pkg is now registered and "world" contains it
487 with pytest.warns(pytest.PytestRemovedIn10Warning, match="legacy namespace"):
488 monkeypatch.syspath_prepend("world")
489 import ns_pkg.world
490
491 assert ns_pkg.world.check() == "world"
492
493 # Should invalidate caches via importlib.invalidate_caches.
494 # Should not warn for path without namespace packages.
495 modules_tmpdir = pytester.mkdir("modules_tmpdir")
496 with warnings.catch_warnings():
497 warnings.simplefilter("error")
498 monkeypatch.syspath_prepend(str(modules_tmpdir))
499
500 modules_tmpdir.joinpath("main_app.py").write_text("app = True", encoding="utf-8")
501 from main_app import app # noqa: F401