def test_default_dict(self): """ test attrdict's defaultdict support. """ from attrdict import AttrDict self.assertRaises(KeyError, lambda: AttrDict()['foo']) self.assertRaises(AttributeError, lambda: AttrDict().foo) adict = AttrDict(default_factory=lambda: ('foo', 'bar', 'baz')) self.assertEqual(adict['foo'], ('foo', 'bar', 'baz')) self.assertEqual(adict('bar'), ('foo', 'bar', 'baz')) self.assertEqual(adict.baz, ('foo', 'bar', 'baz')) self.assertEqual(adict.get('lorem'), None) self.assertEqual(adict.get('ipsum', 'alpha'), 'alpha') # make sure this doesn't break access adict.bravo = 'charlie' self.assertEqual(adict['bravo'], 'charlie') self.assertEqual(adict('bravo'), 'charlie') self.assertEqual(adict.bravo, 'charlie') self.assertEqual(adict.get('bravo'), 'charlie') self.assertEqual(adict.get('bravo', 'alpha'), 'charlie')
def test_default_dict_pass_key(self): """ test attrdict's defaultdict support. """ from attrdict import AttrDict adict = AttrDict(default_factory=lambda foo: (foo, 'bar', 'baz'), pass_key=True) self.assertEqual(adict['foo'], ('foo', 'bar', 'baz')) self.assertEqual(adict('bar'), ('bar', 'bar', 'baz')) self.assertEqual(adict.baz, ('baz', 'bar', 'baz')) self.assertEqual(adict.get('lorem'), None) self.assertEqual(adict.get('ipsum', 'alpha'), 'alpha') # make sure this doesn't break access adict.bravo = 'charlie' self.assertEqual(adict['bravo'], 'charlie') self.assertEqual(adict('bravo'), 'charlie') self.assertEqual(adict.bravo, 'charlie') self.assertEqual(adict.get('bravo'), 'charlie') self.assertEqual(adict.get('bravo', 'alpha'), 'charlie')
def test_default_dict_pass_key(self): """ test attrdict's defaultdict support. """ from attrdict import AttrDict adict = AttrDict(default_factory=lambda foo: (foo, 'bar', 'baz'), pass_key=True) self.assertEqual(adict['foo'], ('foo', 'bar', 'baz')) self.assertEqual(adict('bar'), ('bar', 'bar', 'baz')) self.assertEqual(adict.baz, ('baz', 'bar', 'baz')) self.assertEqual(adict.get('lorem'), None) self.assertEqual(adict.get('ipsum', 'alpha'), 'alpha') # make sure this doesn't break access adict.bravo = 'charlie' self.assertEqual(adict['bravo'], 'charlie') self.assertEqual(adict('bravo'), 'charlie') self.assertEqual(adict.bravo, 'charlie') self.assertEqual(adict.get('bravo'), 'charlie') self.assertEqual(adict.get('bravo', 'alpha'), 'charlie') # make sure missing doesn't happen on hidden attributes adict = AttrDict(default_factory=lambda: 'default') self.assertEqual(adict.works, 'default') self.assertRaises(AttributeError, lambda: adict._hidden) self.assertEqual(adict.get('_hidden'), None) self.assertRaises(AttributeError, lambda: adict.__magic__) self.assertEqual(adict.get('__magic__'), None) # but this should work self.assertEqual(adict('_this_is_fine'), 'default')