Skip to content

Instantly share code, notes, and snippets.

@felipe-prenholato
Created October 9, 2012 04:51
Show Gist options
  • Save felipe-prenholato/3856684 to your computer and use it in GitHub Desktop.
Save felipe-prenholato/3856684 to your computer and use it in GitHub Desktop.
Django unit tests to test singleton
""" Django unit tests to test singleton """
from django.test import TestCase
class Singleton(object):
__instance__ = None
def __new__(cls, *a, **kw):
if Singleton.__instance__ is None:
Singleton.__instance__ = object.__new__(cls, *a, **kw)
cls._Singleton__instance = Singleton.__instance__
return Singleton.__instance__
def _drop_it(self):
Singleton.__instance__ = None
class Foo(Singleton):
"""
Class used in singleton tests
"""
pass
class SingletonTest(TestCase):
def test_singleton(self):
"""
Test singleton implementation with values
"""
a = Foo()
a.attr_1 = 1
b = Foo()
self.assertEqual(b.attr_1, 1)
self.assertTrue(a is b, "'a' isn't 'b', Singleton not works")
def test_singleton_destruction(self):
"""
Test singleton imsinplementation with values and than destroy it
"""
a = Foo()
id_a = id(a)
a.attr_1 = 1
b = Foo()
id_b = id(b)
self.assertEqual(id_a, id_b)
self.assertEqual(b.attr_1, 1)
self.assertTrue(a is b, "'a' isn't 'b', Singleton not works")
a._drop_it()
c = Foo()
id_c = id(c)
self.assertNotEqual(id_a, id_c)
self.assertNotEqual(getattr(c,'attr_1',None), 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment