Skip to content

Instantly share code, notes, and snippets.

@mkroutikov
Created July 13, 2017 19:37
Show Gist options
  • Save mkroutikov/2c0005722fc80b1d5fa562f5cefd1e2d to your computer and use it in GitHub Desktop.
Save mkroutikov/2c0005722fc80b1d5fa562f5cefd1e2d to your computer and use it in GitHub Desktop.
class DomainMap:
_map = None
@classmethod
def _get(cls):
raise NotImplementedError('heavy work done here (someday)')
@classmethod
def get(cls):
if cls._map is None:
cls._map = cls._get()
return cls._map
@classmethod
def reset(cls):
cls._map = None
#####
from unittest import mock
import unittest
class TestDomainMap(unittest.TestCase):
def test_singleton_and_reset(self):
with mock.patch('x.DomainMap._get', mock.Mock(return_value={'foo': 'boo'})):
x = DomainMap.get()
self.assertEquals(x, {'foo': 'boo'})
with mock.patch('x.DomainMap._get', mock.Mock(return_value={'coo': 'doo'})):
x = DomainMap.get()
self.assertEquals(x, {'foo': 'boo'}) # old value, cached!
DomainMap.reset()
with mock.patch('x.DomainMap._get', mock.Mock(return_value={'coo': 'doo'})):
x = DomainMap.get()
self.assertEquals(x, {'coo': 'doo'}) # new value, reset worked!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment