def test_dictionary__callable_not_called(self): """ Test that callable values are returned as-is (and in particular not called). """ def foo_callable(self): return "bar" item = {"foo": foo_callable} self.assertNotEqual(_get_value(item, "foo"), "bar") self.assertTrue(_get_value(item, "foo") is foo_callable)
def test_dictionary__key_present(self): """ Test getting a key from a dictionary. """ item = {"foo": "bar"} self.assertEqual(_get_value(item, "foo"), "bar")
def test_object__non_built_in_type(self): """ Test getting an attribute from an instance of a type that isn't built-in. """ item = datetime(2012, 1, 2) self.assertEqual(_get_value(item, "day"), 2)
def test_object__attribute_is_callable(self): """ Test getting a callable attribute from an object. """ item = SimpleObject() self.assertEqual(_get_value(item, "foo_callable"), "called...")
def test_object__attribute_present(self): """ Test getting an attribute from an object. """ item = SimpleObject() self.assertEqual(_get_value(item, "foo"), "bar")
def test_dictionary__dict_subclass(self): """ Test that subclasses of dict are treated as dictionaries. """ class DictSubclass(dict): pass item = DictSubclass() item["foo"] = "bar" self.assertEqual(_get_value(item, "foo"), "bar")
def test_built_in_type__list(self): """ Test getting from a list. """ class MyList(list): pass item1 = MyList([1, 2, 3]) item2 = [1, 2, 3] self.assertEqual(item1.pop(), 3) self.assertEqual(item2.pop(), 3) self.assertEqual(_get_value(item1, 'pop'), 2) self.assertNotFound(item2, 'pop')
def test_built_in_type__string(self): """ Test getting from a string. """ class MyStr(str): pass item1 = MyStr('abc') item2 = 'abc' self.assertEqual(item1.upper(), 'ABC') self.assertEqual(item2.upper(), 'ABC') self.assertEqual(_get_value(item1, 'upper'), 'ABC') self.assertNotFound(item2, 'upper')
def test_built_in_type__integer(self): """ Test getting from an integer. """ class MyInt(int): pass cust_int = MyInt(10) pure_int = 10 # We have to use a built-in method like __neg__ because "public" # attributes like "real" were not added to Python until Python 2.6, # when the numeric type hierarchy was added: # # http://docs.python.org/library/numbers.html # self.assertEqual(cust_int.__neg__(), -10) self.assertEqual(pure_int.__neg__(), -10) self.assertEqual(_get_value(cust_int, '__neg__'), -10) self.assertNotFound(pure_int, '__neg__')
def assertNotFound(self, item, key): """ Assert that a call to _get_value() returns _NOT_FOUND. """ self.assertIs(_get_value(item, key), _NOT_FOUND)