pytest-subprocess icon indicating copy to clipboard operation
pytest-subprocess copied to clipboard

Support __fspath__ protocol?

Open henryiii opened this issue 3 years ago • 1 comments

It would be nice to support anything that supports PathLike. Most of Python supports it except the subprocess.run calls, so I'd understand if you didn't want to, but it's extremely handy (and, as I said, supported pretty much everywhere else - including the latest main branch of nox). It's easy to do - os.fspath passes through strings and bytes already and calls __fspath__ on anything else.

(Currently, it just silently accepts it and doesn't match, which was confusing me for some time until I realized I'd forgotten to convert to a string on one test register call).

henryiii avatar Oct 17 '22 18:10 henryiii

I guess you mean to support it for registering commands, not for the subprocess.run() itself. I want the plugin to be as close to the original subprocess as possible, but I think that could be done in terms of registering commands. Not sure how the matching should work here, but I'll think about it. Can you provide some usage examples of how you envision it from the user's perspective?

aklajnert avatar Oct 18 '22 07:10 aklajnert

For example:

def which_mock(name: str) -> str | None:
    if name == "cmake":
        return "cmake/path"
    return None

def test_get_requires_for_build_wheel_settings(fp, monkeypatch):
    cmake = Path("cmake/path").resolve()
    monkeypatch.setattr(shutil, "which", which_mock)
    fp.register([os.fspath(cmake), "--version"], stdout="3.18.0")
    # Run something that looks up "cmake" and runs it with the resolved path
    # Note: Path.resolve is broken on Windows + Python < 3.10 if the path doesn't exist,
    # But normally this won't happen for which and we match the broken behavior for the mock.

It would be nicer to just write:

fp.register([cmake, "--version"], stdout="3.18.0")

And have it work, but currently, it doesn't work and doesn't throw an error, it just does not match.

I'm not sure why subprocess.run doesn't support os.Pathlike, it seems like an obvious place to use it.

henryiii avatar Dec 02 '22 16:12 henryiii

Ahh, Guido just pointed out that I'm wrong in my discuss.python.org topic. subprocess.run does take os.PathLike since Python 3.8 (and I forgot, it was only broken on Windows in 3.7).

henryiii avatar Dec 02 '22 19:12 henryiii