testpath
Testpath is a collection of utilities for Python code working with files and commands. It contains functions to check things on the filesystem, and tools for mocking system commands and recording calls to those. The current version is 0.6.0.
Warnings
- gotcha When mocking system commands using `testpath.assert_calls` or similar utilities, `testpath` manipulates the system's `PATH` environment variable. This makes the command mock global to the entire process, affecting all threads and coroutines, not just the isolated test scope. This can lead to unexpected interference and flaky tests in concurrent testing scenarios.
- gotcha The `testpath.assert_calls` utility is specifically designed to mock *external system commands* by replacing them in the system's `PATH`. It does not directly mock Python functions or modules. If your code calls a Python function that then uses `subprocess.run` to execute an external command, `assert_calls` will intercept the *external command*. However, it will not intercept calls to Python functions themselves or if the 'command' is a Python-internal function call disguised as an external command.
Install
-
pip install testpath
Imports
- testpath
import testpath
Quickstart
import tempfile
import os
import testpath
# 1. Asserting filesystem state
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(b"hello world")
temp_file_path = f.name
try:
testpath.assert_isfile(temp_file_path)
print(f"Assertion successful: {temp_file_path} is a file.")
finally:
os.remove(temp_file_path)
# 2. Mocking system commands
def func_that_calls_git():
# In a real scenario, this would execute a 'git' command
# e.g., subprocess.run(['git', 'status'])
print("Simulating a call to 'git status'")
with testpath.assert_calls('git', ['status']):
func_that_calls_git()
print("Mocked 'git status' call intercepted.")