Skip to main content

pytest-subprocess

PyPI version Python versions See Build Status on Azure Pipelines https://codecov.io/gh/aklajnert/pytest-subprocess/branch/master/graph/badge.svg?token=JAU1cGoYL8

A plugin to fake subprocess for pytest

Installation

You can install “pytest-subprocess” via pip from PyPI:

$ pip install pytest-subprocess

Usage

After plugin installation, the fake_subprocess fixture will become available. Use it to register subprocess results so you won’t need to rely on the real processes. The plugin hooks on the subprocess.Popen(), which is the base for other subprocess functions. That makes the subproces.run(), subprocess.call(), subprocess.check_call() and subprocess.check_output() methods also functional.

Basic usage

The most important method is fake_process.register_subprocess() which allows to define the fake processes behavior.

def test_git(fake_process):
    fake_process.register_subprocess(
        ["git", "branch"], stdout=["* fake_branch", "  master"]
    )

    process = subprocess.Popen(
        ["git", "branch"], stdout=subprocess.PIPE, universal_newlines=True
    )
    out, _ = process.communicate()

    assert process.returncode == 0
    assert out == "* fake_branch\n  master\n"

Unregistered commands

By default, when the fake_process fixture is being used, any attempt to run subprocess that has not been registered will raise the ProcessNotRegisteredError exception. To allow it, use fake_process.allow_unregistered(True), which will execute all unregistered processes with real subprocess, or use fake_process.pass_command("command") to allow just a single command.

def test_real_process(fake_process):
    with pytest.raises(pytest_subprocess.ProcessNotRegisteredError):
        # this will fail, as "ls" command is not registered
        subprocess.call("ls")

    fake_process.pass_command("ls")
    # now it should be fine
    assert subprocess.call("ls") == 0

    # allow all commands to be called by real subprocess
    fake_process.allow_unregistered(True)
    assert subprocess.call(["ls", "-l"]) == 0

Differing results

Each register_subprocess() or pass_command() method call will register only one command execution. You can call those methods multiple times, to change the faked output on each subprocess run. When you call subprocess more times than registered command, the ProcessNotRegisteredError will be raised. To prevent that, call fake_process.keep_last_process(True), which will keep the last registered process forever.

def test_different_output(fake_process):
    # register process with output changing each execution
    fake_process.register_subprocess("test", stdout="first execution")
    # the second execution will return non-zero exit code
    fake_process.register_subprocess("test", stdout="second execution", returncode=1)

    assert subprocess.check_output("test") == b"first execution\n"
    second_process = subprocess.run("test", stdout=subprocess.PIPE)
    assert second_process.stdout == b"second execution\n"
    assert second_process.returncode == 1

    # 3rd time shall raise an exception
    with pytest.raises(pytest_subprocess.ProcessNotRegisteredError):
        subprocess.check_call("test")

    # now, register two processes once again, but the last one will be kept forever
    fake_process.register_subprocess("test", stdout="first execution")
    fake_process.register_subprocess("test", stdout="second execution")
    fake_process.keep_last_process(True)

    # now the processes can be called forever
    assert subprocess.check_output("test") == b"first execution\n"
    assert subprocess.check_output("test") == b"second execution\n"
    assert subprocess.check_output("test") == b"second execution\n"
    assert subprocess.check_output("test") == b"second execution\n"

As a context manager

The fake_process fixture provides context() method that allows to use it as a context manager. It can be used to limit the scope when a certain command is allowed, e.g. to make sure that the code doesn’t want to execute it somewhere else.

def test_context_manager(fake_process):
    with pytest.raises(pytest_subprocess.ProcessNotRegisteredError):
        # command not registered, so will raise an exception
        subprocess.check_call("test")

    with fake_process.context() as nested_process:
        nested_process.register_subprocess("test", occurrences=3)
        # now, we can call the command 3 times without error
        assert subprocess.check_call("test") == 0
        assert subprocess.check_call("test") == 0

    # the command was called 2 times, so one occurrence left, but since the
    # context manager has been left, it is not registered anymore
    with pytest.raises(pytest_subprocess.ProcessNotRegisteredError):
        subprocess.check_call("test")

Contributing

Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

License

Distributed under the terms of the MIT license, “pytest-subprocess” is free and open source software

Issues

If you encounter any problems, please file an issue along with a detailed description.


This pytest plugin was generated with Cookiecutter along with @hackebrot’s cookiecutter-pytest-plugin template.

Metadata

Release files for pytest-subprocess 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-subprocess 0.1.1
File Size Uploaded Provenance Actions
pytest-subprocess-0.1.1.tar.gz 10.8 kB Without provenance Details for pytest-subprocess-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-subprocess 0.1.1
File Interpreter ABI Platform Actions
pytest_subprocess-0.1.1-py3-none-any.whl Python 3 none any Details for pytest_subprocess-0.1.1-py3-none-any.whl

Total release size: 20.5 kB

Release files / pytest-subprocess-0.1.1.tar.gz

Download URL pytest-subprocess-0.1.1.tar.gz
Size 10.8 kB
Tags Source
SHA-256 checksum
How to use checksums
f90893109088bbe4d97a9303182287c8f33dc0d94d7b2cf2535516e2343dff7b
BLAKE2b-256 checksum
How to use checksums
2c03894efdd1cc4a16f934e6728b8fc3989d9961fec672c088d22703637ea0d8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/28.8.0 requests-toolbelt/0.9.1 tqdm/4.39.0 CPython/3.6.4

Release files / pytest_subprocess-0.1.1-py3-none-any.whl

Download URL pytest_subprocess-0.1.1-py3-none-any.whl
Size 9.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
de9a89e4b209e1d533e2413d9803890728a37299e06ee0ccf2ea63c616d6a472
BLAKE2b-256 checksum
How to use checksums
d36a4c828bd7b0939969967abf72a48e5c6f2fef20e3e8a6770dca1f967f88bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/28.8.0 requests-toolbelt/0.9.1 tqdm/4.39.0 CPython/3.6.4

Security for pytest-subprocess 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page