Repository: joanvila/aioredlock

Issue:
A function to return number of active locks
Would be a nice to have a feature to do that.

Discussion:

Patch:
diff --git a/aioredlock/algorithm.py b/aioredlock/algorithm.py
index bf192ab..51707b7 100644
--- a/aioredlock/algorithm.py
+++ b/aioredlock/algorithm.py
@@ -238,3 +238,18 @@ class Aioredlock:
         self._watchdogs.clear()
 
         await self.redis.clear_connections()
+
+    async def get_active_locks(self):
+        """
+        Return all stored locks that are valid.
+
+        .. note::
+            This function is only really useful in learning if there are no
+            active locks. It is possible that by the time the a lock is
+            returned from this function that it is no longer active.
+        """
+        ret = []
+        for lock in self._locks.values():
+            if lock.valid is True and await lock.is_locked():
+                ret.append(lock)
+        return ret
diff --git a/aioredlock/lock.py b/aioredlock/lock.py
index a44b84c..58f5b09 100644
--- a/aioredlock/lock.py
+++ b/aioredlock/lock.py
@@ -21,3 +21,6 @@ class Lock:
 
     async def release(self):
         await self.lock_manager.unlock(self)
+
+    async def is_locked(self):
+        return await self.lock_manager.is_locked(self)


Test patch:
diff --git a/tests/ut/conftest.py b/tests/ut/conftest.py
index 7acbe39..7004ad1 100644
--- a/tests/ut/conftest.py
+++ b/tests/ut/conftest.py
@@ -12,8 +12,19 @@ async def dummy_sleep(seconds):
 
 
 @pytest.fixture
-def locked_lock():
-    return Lock(None, "resource_name", 1, -1, True)
+def locked_lock(lock_manager_redis_patched):
+    lock_manager, _ = lock_manager_redis_patched
+    lock = Lock(lock_manager, "resource_name", 1, -1, True)
+    lock_manager._locks[lock.resource] = lock
+    return lock
+
+
+@pytest.fixture
+def unlocked_lock(lock_manager_redis_patched):
+    lock_manager, _ = lock_manager_redis_patched
+    lock = Lock(lock_manager, "other_resource_name", 1, -1, False)
+    lock_manager._locks[lock.resource] = lock
+    return lock
 
 
 @pytest.fixture
diff --git a/tests/ut/test_algorithm.py b/tests/ut/test_algorithm.py
index f4ef3ed..e2655c0 100644
--- a/tests/ut/test_algorithm.py
+++ b/tests/ut/test_algorithm.py
@@ -344,3 +344,13 @@ class TestAioredlock:
 
             await lock_manager.unlock(lock)
             assert lock.valid is False
+
+    @pytest.mark.asyncio
+    async def test_get_active_locks(self, lock_manager_redis_patched, locked_lock, unlocked_lock):
+        lock_manager, redis = lock_manager_redis_patched
+        redis.is_locked.return_value = True
+
+        locks = await lock_manager.get_active_locks()
+
+        assert locked_lock in locks
+        assert unlocked_lock not in locks