|
| 1 | +import builtins |
1 | 2 | import os
|
| 3 | +import re |
2 | 4 | import subprocess
|
3 | 5 | import sys
|
4 | 6 | import time
|
| 7 | +from collections import OrderedDict |
| 8 | +from contextlib import contextmanager |
5 | 9 | from typing import List
|
6 | 10 |
|
7 | 11 | import py.path
|
|
10 | 14 | import pytest
|
11 | 15 | from _pytest.config import ExitCode
|
12 | 16 | from _pytest.config import PytestPluginManager
|
| 17 | +from _pytest.pathlib import Path |
13 | 18 | from _pytest.pytester import CwdSnapshot
|
14 | 19 | from _pytest.pytester import HookRecorder
|
15 | 20 | from _pytest.pytester import LineMatcher
|
@@ -1215,3 +1220,53 @@ def pytest_collect_file(path, parent):
|
1215 | 1220 | "=* 1 failed in *",
|
1216 | 1221 | ]
|
1217 | 1222 | )
|
| 1223 | + |
| 1224 | + |
| 1225 | +def test_testdir_makefiles(testdir: Testdir, monkeypatch: MonkeyPatch) -> None: |
| 1226 | + tmpdir = testdir.tmpdir |
| 1227 | + |
| 1228 | + abspath = str(tmpdir / "bar") |
| 1229 | + created_paths = testdir.makefiles(OrderedDict({"foo": "", abspath: ""})) |
| 1230 | + p1 = created_paths[0] |
| 1231 | + assert isinstance(p1, Path) |
| 1232 | + relpath = tmpdir / "foo" |
| 1233 | + assert str(p1) == str(relpath) |
| 1234 | + |
| 1235 | + p2 = created_paths[1] |
| 1236 | + assert p2.exists() |
| 1237 | + assert str(p2) == abspath |
| 1238 | + |
| 1239 | + assert testdir.makefiles({}) == [] |
| 1240 | + |
| 1241 | + # Disallows creation outside of tmpdir by default. |
| 1242 | + with pytest.raises( |
| 1243 | + ValueError, |
| 1244 | + match="'/abspath' does not start with '{}'".format(re.escape(str(tmpdir))), |
| 1245 | + ): |
| 1246 | + testdir.makefiles({"shouldnotbecreated": "", "/abspath": ""}) |
| 1247 | + # Validation before creating anything. |
| 1248 | + assert not Path("shouldnotbecreated").exists() |
| 1249 | + |
| 1250 | + # Support writing arbitrary files on request. |
| 1251 | + open_calls = [] |
| 1252 | + orig_open = builtins.open |
| 1253 | + |
| 1254 | + @contextmanager |
| 1255 | + def mocked_open(*args): |
| 1256 | + open_calls.append(["__enter__", args]) |
| 1257 | + with orig_open(os.devnull, *args[1:]) as fp: |
| 1258 | + yield fp |
| 1259 | + |
| 1260 | + with monkeypatch.context() as mp: |
| 1261 | + mp.setattr(builtins, "open", mocked_open) |
| 1262 | + created_paths = testdir.makefiles({"/abspath": ""}, allow_outside_tmpdir=True) |
| 1263 | + assert created_paths == [Path("/abspath")] |
| 1264 | + assert open_calls == [["__enter__", ("/abspath", "w")]] |
| 1265 | + |
| 1266 | + # Duplicated files (absolute and relative). |
| 1267 | + created_paths = testdir.makefiles(OrderedDict({"bar": "1", abspath: "2"})) |
| 1268 | + with open("bar", "r") as fp: |
| 1269 | + assert fp.read() == "2" |
| 1270 | + created_paths = testdir.makefiles(OrderedDict({abspath: "2", "bar": "1"})) |
| 1271 | + with open("bar", "r") as fp: |
| 1272 | + assert fp.read() == "1" |
0 commit comments