pytest-shutil
pytest-shutil is a Python library offering a collection of Unix shell and environment management tools specifically designed for automated tests with `pytest`. It provides fixtures and utilities to streamline tasks such as managing temporary directories (workspaces), executing shell commands, and manipulating environment variables within test contexts. Currently at version 1.8.1, it is actively maintained with recent updates addressing Python compatibility and modern best practices.
Warnings
- breaking Version 1.8.0 dropped support for Python 2 and Python versions less than 3.6. Code relying on older Python syntax or features will break.
- breaking As of version 1.8.0, `pytest-shutil` replaced `path.py` with `pathlib` for path objects and switched from the `mock` package to Python's standard library `unittest.mock`. Code directly interacting with `path.py` objects or the external `mock` library within `pytest-shutil`'s context will need updates.
- gotcha Since version 1.1.0, `workspace.run()`'s default behavior changed to *not* use a subshell for security reasons. If your command requires shell features (e.g., pipes, redirects, environment variable expansion like `$VAR`), you must explicitly pass `shell=True` to `workspace.run()`.
Install
-
pip install pytest-shutil
Imports
- workspace
def test_something(workspace):
- run
from pytest_shutil.run import run
- set_env
from pytest_shutil.env import set_env
Quickstart
import pytest
from pathlib import Path
# To make the workspace fixture available, pytest-shutil must be installed.
# No explicit import is usually needed for fixtures when installed as a plugin.
def test_create_file_and_run_script(workspace):
"""Demonstrates using the workspace fixture to create a file and run a shell command."""
# 'workspace' is a pathlib.Path object pointing to a temporary directory
assert isinstance(workspace.workspace, Path)
# Create a simple shell script in the workspace
script_content = """#!/bin/bash
echo "Hello from $1!"
"""
script_path = workspace.workspace / 'hello.sh'
script_path.write_text(script_content)
script_path.chmod(0o755) # Make it executable
# Run the script relative to the workspace
result = workspace.run('./hello.sh World', check=True, capture=True)
assert result.returncode == 0
assert "Hello from World!" in result.stdout
print(result.stdout)