Mount ISO Loop Device Mock Script in Python
Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.
Python code
44 linesimport os
import tempfile
from dataclasses import dataclass
from pathlib import Path
@dataclass
class LoopDevice:
path: str
iso_path: str
mounted: bool = False
def mount(self, mount_point: str):
if self.mounted:
raise RuntimeError(f"Loop device {self.path} already mounted")
os.makedirs(mount_point, exist_ok=True)
self.mounted = True
self.mount_point = mount_point
print(f"MOUNT: {self.iso_path} -> {mount_point} via {self.path}")
def unmount(self):
if not self.mounted:
raise RuntimeError(f"Loop device {self.path} not mounted")
self.mounted = False
print(f"UNMOUNT: {self.iso_path} released from {self.path}")
def mount_iso(iso_path: str, mount_point: str) -> LoopDevice:
if not Path(iso_path).exists():
raise FileNotFoundError(f"ISO file not found: {iso_path}")
device = LoopDevice(path="/dev/loop0", iso_path=iso_path)
device.mount(mount_point)
return device
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmpdir:
iso = Path(tmpdir) / "test.iso"
iso.touch() # simulate existing ISO file
mount_dir = Path(tmpdir) / "mnt"
dev = mount_iso(str(iso), str(mount_dir))
print(f"Device: {dev.path}, Mounted: {dev.mounted}")
print(f"ISO content visible at: {mount_dir}")
dev.unmount()
print(f"Device: {dev.path}, Mounted: {dev.mounted}")
Output
MOUNT: /tmp/xxxx/test.iso -> /tmp/xxxx/mnt via /dev/loop0
Device: /dev/loop0, Mounted: True
ISO content visible at: /tmp/xxxx/mnt
UNMOUNT: /tmp/xxxx/test.iso released from /dev/loop0
Device: /dev/loop0, Mounted: False
How it works
The LoopDevice dataclass encapsulates mount state in a single object, preventing double-mount and duplicate-unmount bugs. mount_iso() checks the ISO exists before creating a device, failing fast with FileNotFoundError. The script uses tempfile.TemporaryDirectory() so no filesystem cleanup is needed after the test. The mock prints clear MOUNT/UNMOUNT messages so you can trace exactly what the script would do in production. This approach lets you test bind-mount logic, backup flows, or an installer's ISO handling without root privileges.
Common mistakes
- Forgetting to check `self.mounted` before mounting, leading to silent duplicate mounts.
- Trying to access `self.mount_point` before it's set, causing an `AttributeError`.
- Assuming a real loop device is available — the mock only simulates behavior.
- Not using `tempfile.TemporaryDirectory()`, leaving mount-point folders behind.
Variations
- Add a `detach_loop()` method that resets the device path for reuse.
- Use `functools.lru_cache` to cache mount results for repeated calls with the same ISO.
Real-world use cases
- Testing an installer script's ISO handling before deploying to real Linux hosts.
- Simulating mount/unmount in unit tests for backup tools that iterate mounted media.
- Prototyping a system-admin automation that mounts ISOs on servers without full root access.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.