How to Mock a pyenv Local Version File in Python
Read and write a mock .python-version file using the pathlib module and tempfile for isolated testing.
Python code
25 linesimport json
import tempfile
from pathlib import Path
def read_pyenv_local(directory: Path) -> str:
"""Read the .python-version file in the given directory."""
version_file = directory / ".python-version"
if not version_file.exists():
return "no-version-file"
return version_file.read_text().strip()
def write_pyenv_local(directory: Path, version: str) -> None:
"""Write a mock .python-version file."""
(directory / ".python-version").write_text(version + "\n")
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
project_dir = Path(tmp) / "my_project"
project_dir.mkdir()
write_pyenv_local(project_dir, "3.11.5")
result = read_pyenv_local(project_dir)
print(json.dumps({"project": project_dir.name, "version": result}))
Output
{"project": "my_project", "version": "3.11.5"}
How it works
The script creates a temporary directory with tempfile.TemporaryDirectory, then writes a mock .python-version file using Path.write_text. The read_pyenv_local function checks if the file exists and returns its contents stripped of trailing whitespace. This mimics the pyenv version file behavior for testing or building tools that depend on it. Using tempfile ensures the test doesn't pollute the filesystem and cleans up automatically.
Common mistakes
- Forgetting to strip newline characters from the read version string
- Checking for the file before creating the directory structure
- Not using a temporary directory, which leaves test artifacts behind
Variations
- Use `unittest.mock.patch` with `mock_open` to avoid real file I/O
- Parse the version file with `tomllib` if you need TOML support instead
Real-world use cases
- Testing a project setup script that validates Python version constraints before installing dependencies.
- Building a CI pipeline helper that reads the pinned version to choose the correct runner image.
- Creating a local development bootstrapper that verifies the environment file matches the required runtime.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.