Skip to content

Commit d5aa8e6

Browse files
authored
Merge pull request #302 from joshuagl/joshuagl/one-filesystem-backend-to-rule-them-all
storage: make FilesystemBackend a singleton
2 parents c6a8f4b + 60886f6 commit d5aa8e6

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

securesystemslib/storage.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,20 @@ class FilesystemBackend(StorageBackendInterface):
188188
local filesystems using Python standard library functions.
189189
"""
190190

191+
# As FilesystemBackend is effectively a stateless wrapper around various
192+
# standard library operations, we only ever need a single instance of it.
193+
# That single instance is safe to be (re-)used by all callers. Therefore
194+
# implement the singleton pattern to avoid uneccesarily creating multiple
195+
# objects.
196+
_instance = None
197+
198+
def __new__(cls, *args, **kwargs):
199+
if cls._instance is None:
200+
cls._instance = object.__new__(cls, *args, **kwargs)
201+
return cls._instance
202+
203+
204+
191205
class GetFile(object):
192206
# Implementing get() as a function with the @contextmanager decorator
193207
# doesn't allow us to cleanly capture exceptions thrown by the underlying

tests/test_storage.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,15 @@ def test_folders(self):
100100
fi.write(leaf.encode('utf-8'))
101101
found_leaves = self.storage_backend.list_folder(folder)
102102
self.assertListEqual(leaves, sorted(found_leaves))
103+
104+
105+
def test_singleton(self):
106+
# There should only ever be a single instance of FilesystemBackend.
107+
# An object's id is unique and constant for the object during its
108+
# lifetime. Therefore create more than one instance of FilesystemBackend
109+
# and compare their id's
110+
fb1 = securesystemslib.storage.FilesystemBackend()
111+
fb2 = securesystemslib.storage.FilesystemBackend()
112+
self.assertEqual(id(fb1), id(fb2))
113+
self.assertEqual(id(self.storage_backend), id(fb1))
114+
self.assertEqual(id(fb2), id(self.storage_backend))

0 commit comments

Comments
 (0)