Skip to content

Instantly share code, notes, and snippets.

@dpwiz
Created May 25, 2011 12:33
Show Gist options
  • Save dpwiz/990870 to your computer and use it in GitHub Desktop.
Save dpwiz/990870 to your computer and use it in GitHub Desktop.
Partial(dict) with extra helpers for nose
"""Partial(dict) with extra helpers for nose.
>>> data = {'spam': 'salad', 'sausage': 'spam', 'whatever': 42}
Check only what you care for:
>>> data == {'spam': 'salad'}
False
>>> data == Partial({'spam': 'salad'})
True
Use dict() syntax, check inside dicts and ignore values:
>>> data['inquisition'] = {'expected': False}
>>> data == Partial(inquisition={'expected': Whatever()})
True
Nose-like shortcut to type less stuff:
>>> pe_(data, {'spam': 'salad'}, whatever=Whatever())
>>> pe_("something like eq_(True, bool(...))")
Check for more tests/examples at the bottom.
Latest version: https://gist.github.com/990870
"""
try:
from nose.tools import eq_
def pe_(have, __should={}, **shouldcut):
"""Partial-equal shortcut for nose eq_"""
__should = dict(__should, **shouldcut)
if not __should:
return eq_(True, bool(have)) # like assert, baby!
eq_(have, Partial(__should))
except ImportError:
pass
class Whatever(object):
"""Dummy object to check against"""
def __repr__(self):
return "Whatever()"
class Partial(dict):
"""Check if we're included in other dict"""
def __repr__(self):
return "Partial(%s)" % dict.__repr__(self)
def __eq__(self, other):
if not isinstance(other, dict):
# duh..
return False
for key, value in self.iteritems():
if key not in other:
# keys should be there as requested
return False
if isinstance(value, Whatever):
# but maybe we don't care about values
continue
if isinstance(value, dict) and not isinstance(value, Partial):
# propagate our laziness
value = Partial(value)
if other[key] != value:
# oh... real work
return False
return True
def __ne__(self, other):
return not self == other
def test_partial():
data = {
'sausage': 'spam',
'salad': 'eggs',
'whatever': 42,
'inquisition': {
'spanish': True,
'expected': False,
'by': 'nobody'
}
}
eq_(Partial({'salad': 'eggs'}), data) # key and value are in place and exact
eq_(Partial(sausage=Whatever()), data) # ignore value; check our kwargs stuff
eq_(False, (Partial({'test': Whatever()}) == data)) # has no key
eq_(False, (data == Partial({'test': Whatever()}))) # in reverse
eq_(data['inquisition'], Partial(spanish=True)) # pre-check
eq_(data, Partial(inquisition={'spanish': True, 'expected': Whatever()})) # check insides
eq_(False, data == Partial(inquisition={'expected': True, 'by': 'YOU'}))
eq_(False, 'True value but not a dict' == Partial())
# shortcuts are useful indeed
pe_(data, {'whatever': 42})
pe_(data, salad='eggs')
pe_(data, {'sausage': Whatever()}, whatever=Whatever()) # whatever... hybrid dict/args sugar
pe_(data) # okay.jpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment