From d6c421faf33d2059872bf7918b7e31a1b4eee54e Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Sun, 8 Aug 2021 09:20:18 +0000 Subject: [PATCH] loop: add LoopInfo.is_bound_to helper Add a helper that will check if the loop devices is backed by the file identified via the stat(2) result, i.e. the inode on the correspoding device. Add a correspoding test for the new helper. --- osbuild/loop.py | 5 +++++ test/mod/test_loop.py | 12 +++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/osbuild/loop.py b/osbuild/loop.py index 96dab6fc..9d7e2931 100644 --- a/osbuild/loop.py +++ b/osbuild/loop.py @@ -43,6 +43,11 @@ class LoopInfo(ctypes.Structure): """Return if `LO_FLAGS_AUTOCLEAR` is set in `lo_flags`""" return bool(self.lo_flags & Loop.LO_FLAGS_AUTOCLEAR) + def is_bound_to(self, info: os.stat_result) -> bool: + """Return if the loop device is bound to the file `info`""" + return (self.lo_device == info.st_dev and + self.lo_inode == info.st_ino) + class Loop: """Loopback device diff --git a/test/mod/test_loop.py b/test/mod/test_loop.py index e6800821..5fbb8499 100644 --- a/test/mod/test_loop.py +++ b/test/mod/test_loop.py @@ -4,7 +4,7 @@ import contextlib import os -from tempfile import TemporaryDirectory +from tempfile import TemporaryDirectory, TemporaryFile import pytest @@ -46,6 +46,16 @@ def test_basic(tempdir): assert info.lo_inode == sb.st_ino assert info.lo_number == lo.minor + # check for `LoopInfo.is_bound_to` helper + assert info.is_bound_to(sb) + + with TemporaryFile(dir=tempdir) as t: + t.write(b"") + t.flush() + + st = os.fstat(t.fileno()) + assert not info.is_bound_to(st) + # check for autoclear flags setting and helpers assert info.autoclear