Skip to content

Instantly share code, notes, and snippets.

@allancaffee
Created May 4, 2011 12:09
Show Gist options
  • Save allancaffee/955125 to your computer and use it in GitHub Desktop.
Save allancaffee/955125 to your computer and use it in GitHub Desktop.
A potential deterministic dingus implementation (and test)
from dingus import Dingus
class DeterministicDingus(Dingus):
"""This dingus returns a different Dingus depending on the arguments it's called with.
It has the property of being purely deterministic (i.e. the same
arguments always return the same object). Unfortunately this
means that the behaviour of returning an identical `Dingus` when
called without arguments is lost.
>>> d = DeterministicDingus()
>>> d('an arg') == d('other arg')
False
>>> d('an arg') == d('an arg')
True
>>> d.func('an arg') == d.func('other arg')
False
>>> d.func('an arg') == d.func('an arg')
True
>>> d.func('an arg') == d.func()
False
"""
def __init__(self, *args, **kwargs):
self.__argument_map = {}
Dingus.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs):
key = (tuple(args), tuple(kwargs.items()),)
if key in self.__argument_map:
rv = self.__argument_map[key]
else:
self.__argument_map[key] = rv = self._create_child('()')
self._children['()'] = rv
self._log_call('()', args, kwargs, rv)
return rv
from dingus import Dingus
from deterministic_dingus import DeterministicDingus
import deterministic_dingus as mod
class WhenComparingDingusResults(object):
def setup(self):
self.dingus = DeterministicDingus()
def when_calling_with_identical_args_should_be_equal(self):
assert self.dingus('an arg') == self.dingus('an arg')
assert self.dingus() == self.dingus()
assert self.dingus(foo='bar') == self.dingus(foo='bar')
def when_calling_with_different_args_should_not_be_equal(self):
assert self.dingus('an arg') != self.dingus('other arg')
assert self.dingus('an arg') != self.dingus()
assert self.dingus(foo='bar') != self.dingus(biz='bat')
assert self.dingus(foo='bar') != self.dingus(foo='not bar')
assert self.dingus(foo='bar') != self.dingus()
class WhenGettingAttribute(object):
def setup(self):
self.dingus = DeterministicDingus()
def should_return_deterministic_dingus(self):
assert type(self.dingus.my_func) == DeterministicDingus
class WhenCalling(object):
def setup(self):
self.dingus = DeterministicDingus()
self.args = (Dingus(), Dingus(),)
self.kwargs = {'foo': Dingus(), 'bar': Dingus()}
self.dingus(*self.args, **self.kwargs)
def should_record_calls(self):
assert self.dingus.calls('()', *self.args, **self.kwargs)
class WhenCallingAttribute(object):
def setup(self):
self.dingus = DeterministicDingus()
self.args = (Dingus(), Dingus(),)
self.kwargs = {'foo': Dingus(), 'bar': Dingus()}
self.dingus.my_function(*self.args, **self.kwargs)
def should_record_calls(self):
assert self.dingus.calls('my_function', *self.args, **self.kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment