Skip to content

Commit

Permalink
Merge pull request #302 from joshuagl/joshuagl/one-filesystem-backend…
Browse files Browse the repository at this point in the history
…-to-rule-them-all

storage: make FilesystemBackend a singleton
  • Loading branch information
joshuagl authored Nov 25, 2020
2 parents c6a8f4b + 60886f6 commit d5aa8e6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions securesystemslib/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,20 @@ class FilesystemBackend(StorageBackendInterface):
local filesystems using Python standard library functions.
"""

# As FilesystemBackend is effectively a stateless wrapper around various
# standard library operations, we only ever need a single instance of it.
# That single instance is safe to be (re-)used by all callers. Therefore
# implement the singleton pattern to avoid uneccesarily creating multiple
# objects.
_instance = None

def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance



class GetFile(object):
# Implementing get() as a function with the @contextmanager decorator
# doesn't allow us to cleanly capture exceptions thrown by the underlying
Expand Down
12 changes: 12 additions & 0 deletions tests/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,15 @@ def test_folders(self):
fi.write(leaf.encode('utf-8'))
found_leaves = self.storage_backend.list_folder(folder)
self.assertListEqual(leaves, sorted(found_leaves))


def test_singleton(self):
# There should only ever be a single instance of FilesystemBackend.
# An object's id is unique and constant for the object during its
# lifetime. Therefore create more than one instance of FilesystemBackend
# and compare their id's
fb1 = securesystemslib.storage.FilesystemBackend()
fb2 = securesystemslib.storage.FilesystemBackend()
self.assertEqual(id(fb1), id(fb2))
self.assertEqual(id(self.storage_backend), id(fb1))
self.assertEqual(id(fb2), id(self.storage_backend))

0 comments on commit d5aa8e6

Please sign in to comment.