Skip to content

Commit

Permalink
Add a singleton metaclass for IncogniaAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
aninhalbuquerque committed Sep 19, 2024
1 parent 9eed693 commit c9fcaeb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 2 additions & 1 deletion incognia/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@
from .exceptions import IncogniaHTTPError, IncogniaError
from .json_util import encode
from .models import Coordinates, StructuredAddress, TransactionAddress, PaymentValue, PaymentMethod
from .singleton import Singleton
from .token_manager import TokenManager
from .base_request import BaseRequest, JSON_CONTENT_HEADER


class IncogniaAPI:
class IncogniaAPI(metaclass=Singleton):
def __init__(self, client_id: str, client_secret: str):
self.__token_manager = TokenManager(client_id, client_secret)
self.__request = BaseRequest()
Expand Down
8 changes: 8 additions & 0 deletions incognia/singleton.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

class Singleton(type):
_instances = {}

def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
6 changes: 6 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@ class TestIncogniaAPI(TestCase):
})
DEFAULT_PARAMS: Final[None] = None

def test_metaclass_singleton_should_always_return_the_same_instance(self):
api1 = IncogniaAPI(self.CLIENT_ID, self.CLIENT_SECRET)
api2 = IncogniaAPI(self.CLIENT_ID, self.CLIENT_SECRET)

self.assertEqual(api1, api2)

@patch.object(BaseRequest, 'post')
@patch.object(TokenManager, 'get', return_value=TOKEN_VALUES)
def test_register_new_signup_when_installation_id_is_valid_should_return_a_valid_dict(
Expand Down

0 comments on commit c9fcaeb

Please sign in to comment.