Skip to content

Commit

Permalink
refactor: make the ITService class a singleton
Browse files Browse the repository at this point in the history
RHCLOUD-29641
  • Loading branch information
MikelAlejoBR committed Feb 20, 2024
1 parent db307a0 commit 901cd49
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions rbac/management/principal/it_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ def limit_offset_validation(offset, limit):
class ITService:
"""A class to handle interactions with the IT service."""

# Instance variable for the class.
_instance = None

def __new__(cls, *args, **kwargs):
"""Create a single instance of the class."""
if cls._instance is None:
cls._instance = super().__new__(cls, *args, **kwargs)

return cls._instance

def __init__(self):
"""Establish IT connection information."""
self.host = settings.IT_SERVICE_HOST
Expand Down
17 changes: 17 additions & 0 deletions tests/management/principal/test_it_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ class ITServiceTests(IdentityRequest):
def setUp(self):
self.it_service = ITService()

def test_it_service_singleton(self):
"""Test that the IT Service class only gets instantiated once."""
class_instances = [
ITService(),
ITService(),
ITService(),
ITService(),
ITService(),
]

for instance in class_instances:
self.assertEqual(
self.it_service,
instance,
"no new instances of the IT service class should have been created since it is supposed to be a singleton",
)

@mock.patch("management.principal.it_service.ITService._is_service_account_valid")
def test_is_service_account_valid_by_username_client_id(self, _is_service_account_valid: mock.Mock):
"""Test that the function under test calls the underlying function with the unmodified client ID."""
Expand Down

0 comments on commit 901cd49

Please sign in to comment.