How to Create a Mock Virtualenv with an Activation Script in Python
Create a mock virtualenv directory with a generated bash activation script using Python's standard library.
Python code
31 linesimport os
import subprocess
import sys
from pathlib import Path
def mock_virtualenv(name: str = "myenv") -> Path:
"""Create a mock virtualenv directory and activation script."""
env_dir = Path(name)
env_dir.mkdir(exist_ok=True)
(env_dir / "bin").mkdir(exist_ok=True)
activate_script = f"""#!/bin/bash
# Mock activate script for {name}
export VIRTUAL_ENV="{env_dir.resolve()}"
export PATH="$VIRTUAL_ENV/bin:$PATH"
echo "Activated virtualenv: $VIRTUAL_ENV"
"""
activate_path = env_dir / "bin" / "activate"
activate_path.write_text(activate_script)
activate_path.chmod(0o755)
return env_dir
if __name__ == "__main__":
venv_dir = mock_virtualenv()
print(f"Mock venv created at: {venv_dir}")
print(f"Activate with: source {venv_dir / 'bin' / 'activate'}")
print(f"Activate script contents:\n{(venv_dir / 'bin' / 'activate').read_text()}")
Output
Mock venv created at: myenv
Activate with: source myenv/bin/activate
Activate script contents:
#!/bin/bash
# Mock activate script for myenv
export VIRTUAL_ENV="/absolute/path/to/myenv"
export PATH="$VIRTUAL_ENV/bin:$PATH"
echo "Activated virtualenv: $VIRTUAL_ENV"
How it works
The function creates a directory structure mimicking a real virtualenv, including a bin folder. It writes a bash script that sets VIRTUAL_ENV and PATH environment variables when sourced. The chmod(0o755) call makes the script executable. Using Path.write_text ensures the script is written to disk cleanly. This is useful for testing tools that inspect or interact with virtualenv structures without actually creating one.
Common mistakes
- Forgetting to make the script executable with chmod when testing shell integration
- Hardcoding paths instead of using `Path.resolve()` for portability
- Not handling the script name for Windows environments with different activation patterns
Variations
- Use `tempfile.TemporaryDirectory()` to create the mock inside a temporary location for tests
- Generate a PowerShell activate script for Windows compatibility alongside the bash one
Real-world use cases
- Testing CI/CD scripts that validate virtualenv activation without installing dependencies.
- Generating lightweight sandbox environments for tutorial or documentation examples.
- Validating that internal tooling detects and reports on virtualenv paths correctly.
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.