From e33b6e8154e31b3728c597fdfb18e4c7444d1f8c Mon Sep 17 00:00:00 2001 From: Kieran Prasch Date: Thu, 1 Mar 2018 19:03:32 -0800 Subject: [PATCH] [KMS-ETH]- Enhances the singleton pattern for blockchain, adding a way to retrieve the instance. --- nkms_eth/blockchain.py | 17 ++++++++++++----- tests/conftest.py | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/nkms_eth/blockchain.py b/nkms_eth/blockchain.py index a49ae0e43..a1e1e5ae6 100644 --- a/nkms_eth/blockchain.py +++ b/nkms_eth/blockchain.py @@ -13,7 +13,7 @@ class Blockchain: """ _network = '' - _instance = False + _instance = None class AlreadyRunning(Exception): pass @@ -28,10 +28,10 @@ class Blockchain: """ # Singleton - if Blockchain._instance is True: - class_name = self.__class__.__name__ - raise Blockchain.AlreadyRunning('{} is already running. Use .get() to retrieve'.format(class_name)) - Blockchain._instance = True + if Blockchain._instance is not None: + message = 'Blockchain: is already running. Use .get() to retrieve'.format(self._network) + raise Blockchain.AlreadyRunning(message) + Blockchain.__instance = self if populus_config is None: populus_config = PopulusConfig() @@ -43,6 +43,13 @@ class Blockchain: # Opens and preserves connection to a running populus blockchain self._chain = self._project.get_chain(self._network).__enter__() + @classmethod + def get(cls): + if cls._instance is None: + class_name = cls.__name__ + raise Exception('{} has not been created.'.format(class_name)) + return cls._instance + def disconnect(self): self._chain.__exit__(None, None, None) diff --git a/tests/conftest.py b/tests/conftest.py index 00b57112e..777654876 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,7 +10,7 @@ def testerchain(): chain = TesterBlockchain() yield chain del chain - Blockchain._instance = False + TesterBlockchain._instance = None @pytest.fixture(scope='function')