Hi SO's,
Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing? I've started with a basic example and built it up into a testbench so I can see whats going on. Now I don't know how to get rid of it!
Many thanks!!
import sys
import logging
import unittest
LOGLEVEL = logging.DEBUG
class Singleton:
""" A python singleton """
class __impl:
""" Implementation of the singleton interface """
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
def id(self):
""" Test method, return singleton id """
return id(self)
# storage for the instance reference
__instance = None
def __init__(self):
""" Create singleton instance """
# Check whether we already have an instance
if Singleton.__instance is None:
# Create and remember instance
Singleton.__instance = Singleton.__impl()
# Store instance reference as the only member in the handle
self.__dict__['_Singleton__instance'] = Singleton.__instance
def __getattr__(self, attr):
""" Delegate access to implementation """
return getattr(self.__instance, attr)
def __setattr__(self, attr, value):
""" Delegate access to implementation """
return setattr(self.__instance, attr, value)
class A:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
self.lowclass = Singleton()
self.id = self.lowclass.id()
self.log.debug("ID: %s" % self.id)
class B:
def __init__(self):
self.log = logging.getLogger()
self.log.debug("Init %s" % self.__class__.__name__)
self.lowclass = Singleton()
self.id = self.lowclass.id()
self.log.debug("ID: %s" % self.id)
class ATests(unittest.TestCase):
def testOne(self):
a = A()
aid = a.id
b = B()
bid = b.id
self.assertEqual(a.id, b.id)
#
# How do I destroy this thing??
#
del a
del b
a1 = A()
a1id = a1.id
self.assertNotEqual(a1id, aid)
if __name__ == '__main__':
# Set's up a basic logger
logging.basicConfig( format="%(asctime)s %(levelname)-8s %(module)s %(funcName)s %(message)s",
datefmt="%H:%M:%S", stream=sys.stderr )
log = logging.getLogger("")
log.setLevel(LOGLEVEL)
#
suite = unittest.TestLoader().loadTestsFromTestCase(ATests)
sys.exit(unittest.TextTestRunner(verbosity=LOGLEVEL).run(suite))