|
| 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
|
|
11 | 13 | from _pytest.config import PytestPluginManager
|
12 | 14 | from _pytest.main import ExitCode
|
13 | 15 | from _pytest.outcomes import Failed
|
| 16 | +from _pytest.pathlib import Path |
14 | 17 | from _pytest.pytester import CwdSnapshot
|
15 | 18 | from _pytest.pytester import HookRecorder
|
16 | 19 | from _pytest.pytester import LineMatcher
|
| 20 | +from _pytest.pytester import MonkeyPatch |
17 | 21 | from _pytest.pytester import SysModulesSnapshot
|
18 | 22 | from _pytest.pytester import SysPathsSnapshot
|
19 | 23 | from _pytest.pytester import Testdir
|
@@ -704,3 +708,45 @@ def test_error2(bad_fixture):
|
704 | 708 | result.assert_outcomes(error=2)
|
705 | 709 |
|
706 | 710 | assert result.parseoutcomes() == {"error": 2}
|
| 711 | + |
| 712 | + |
| 713 | +def test_testdir_makefiles(testdir: Testdir, monkeypatch: MonkeyPatch) -> None: |
| 714 | + tmpdir = testdir.tmpdir |
| 715 | + |
| 716 | + abspath = str(tmpdir / "bar") |
| 717 | + |
| 718 | + created_paths = testdir.makefiles({"foo": "", abspath: ""}) |
| 719 | + p1 = created_paths[0] |
| 720 | + assert isinstance(p1, Path) |
| 721 | + relpath = tmpdir / "foo" |
| 722 | + assert p1 == relpath |
| 723 | + |
| 724 | + p2 = created_paths[1] |
| 725 | + assert p2.exists() |
| 726 | + assert str(p2) == abspath |
| 727 | + |
| 728 | + assert testdir.makefiles({}) == [] |
| 729 | + |
| 730 | + # Disallows creation outside of tmpdir by default. |
| 731 | + with pytest.raises( |
| 732 | + ValueError, match="'/abspath' does not start with '{}'".format(tmpdir) |
| 733 | + ): |
| 734 | + testdir.makefiles({"shouldnotbecreated": "", "/abspath": ""}) |
| 735 | + # Validation before creating anything. |
| 736 | + assert not Path("shouldnotbecreated").exists() |
| 737 | + |
| 738 | + # Support writing arbitrary files on request. |
| 739 | + open_calls = [] |
| 740 | + orig_open = builtins.open |
| 741 | + |
| 742 | + @contextmanager |
| 743 | + def mocked_open(*args): |
| 744 | + open_calls.append(["__enter__", args]) |
| 745 | + with orig_open(os.devnull, *args[1:]) as fp: |
| 746 | + yield fp |
| 747 | + |
| 748 | + with monkeypatch.context() as mp: |
| 749 | + mp.setattr(builtins, "open", mocked_open) |
| 750 | + created_paths = testdir.makefiles({"/abspath": ""}, allow_outside_tmpdir=True) |
| 751 | + assert created_paths == [Path("/abspath")] |
| 752 | + assert open_calls == [["__enter__", ("/abspath", "w")]] |
0 commit comments