diff --git a/rbac/management/principal/it_service.py b/rbac/management/principal/it_service.py index c84029033..623988d40 100644 --- a/rbac/management/principal/it_service.py +++ b/rbac/management/principal/it_service.py @@ -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 diff --git a/tests/management/principal/test_it_service.py b/tests/management/principal/test_it_service.py index ef1ac769a..1d1eadbbc 100644 --- a/tests/management/principal/test_it_service.py +++ b/tests/management/principal/test_it_service.py @@ -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."""