|
| 1 | +import builtins |
1 | 2 | import os
|
2 | 3 | import subprocess
|
3 | 4 | import sys
|
4 | 5 | import time
|
| 6 | +from contextlib import contextmanager |
5 | 7 | from typing import List
|
6 | 8 |
|
7 | 9 | import py.path
|
|
15 | 17 | from _pytest.pytester import CwdSnapshot
|
16 | 18 | from _pytest.pytester import HookRecorder
|
17 | 19 | from _pytest.pytester import LineMatcher
|
| 20 | +from _pytest.pytester import MonkeyPatch |
18 | 21 | from _pytest.pytester import SysModulesSnapshot
|
19 | 22 | from _pytest.pytester import SysPathsSnapshot
|
20 | 23 | from _pytest.pytester import Testdir
|
@@ -713,16 +716,43 @@ def test_error2(bad_fixture):
|
713 | 716 | assert result.parseoutcomes() == {"error": 2}
|
714 | 717 |
|
715 | 718 |
|
716 |
| -def test_testdir_makefiles(testdir: Testdir) -> None: |
717 |
| - abspath = str(testdir.tmpdir / "bar") |
718 |
| - created_paths = testdir.makefiles(**{"foo": "", abspath: ""}) |
| 719 | +def test_testdir_makefiles(testdir: Testdir, monkeypatch: MonkeyPatch) -> None: |
| 720 | + tmpdir = testdir.tmpdir |
| 721 | + |
| 722 | + abspath = str(tmpdir / "bar") |
| 723 | + |
| 724 | + created_paths = testdir.makefiles({"foo": "", abspath: ""}) |
719 | 725 | p1 = created_paths[0]
|
720 | 726 | assert isinstance(p1, Path)
|
721 |
| - relpath = testdir.tmpdir / "foo" |
| 727 | + relpath = tmpdir / "foo" |
722 | 728 | assert p1 == relpath
|
723 | 729 |
|
724 | 730 | p2 = created_paths[1]
|
725 | 731 | assert p2.exists()
|
726 | 732 | assert str(p2) == abspath
|
727 | 733 |
|
728 |
| - assert testdir.makefiles() == [] |
| 734 | + assert testdir.makefiles({}) == [] |
| 735 | + |
| 736 | + # Disallows creation outside of tmpdir by default. |
| 737 | + with pytest.raises( |
| 738 | + ValueError, match="'/abspath' does not start with '{}'".format(tmpdir) |
| 739 | + ): |
| 740 | + testdir.makefiles({"shouldnotbecreated": "", "/abspath": ""}) |
| 741 | + # Validation before creating anything. |
| 742 | + assert not Path("shouldnotbecreated").exists() |
| 743 | + |
| 744 | + # Support writing arbitrary files on request. |
| 745 | + open_calls = [] |
| 746 | + orig_open = builtins.open |
| 747 | + |
| 748 | + @contextmanager |
| 749 | + def mocked_open(*args): |
| 750 | + open_calls.append(["__enter__", args]) |
| 751 | + with orig_open(os.devnull, *args[1:]) as fp: |
| 752 | + yield fp |
| 753 | + |
| 754 | + with monkeypatch.context() as mp: |
| 755 | + mp.setattr(builtins, "open", mocked_open) |
| 756 | + created_paths = testdir.makefiles({"/abspath": ""}, allow_outside_tmpdir=True) |
| 757 | + assert created_paths == [Path("/abspath")] |
| 758 | + assert open_calls == [["__enter__", ("/abspath", "w")]] |
0 commit comments