diff options
| author | Jenkins <jenkins@review.openstack.org> | 2012-07-23 15:01:11 +0000 |
|---|---|---|
| committer | Gerrit Code Review <review@openstack.org> | 2012-07-23 15:01:11 +0000 |
| commit | 1e2298fadb38280b46c811e1feb43f4e9244de77 (patch) | |
| tree | df25ba1f6fe83489ead1ced4f2f80d1a7074923e | |
| parent | effdfc322413233f2449d229013e1cf21b943127 (diff) | |
| parent | 9e1bd9d9313a9f324c5b7b02232e8bd2fd12ea8a (diff) | |
| download | oslo-1e2298fadb38280b46c811e1feb43f4e9244de77.tar.gz oslo-1e2298fadb38280b46c811e1feb43f4e9244de77.tar.xz oslo-1e2298fadb38280b46c811e1feb43f4e9244de77.zip | |
Merge changes I536e1ca0,Ifb878368,Ie1d71b85
* changes:
Add missing convert_instances arg.
Track to_primitive() depth after iteritems().
Update iteritems test case to actually test iteritems.
| -rw-r--r-- | openstack/common/jsonutils.py | 6 | ||||
| -rw-r--r-- | tests/unit/test_jsonutils.py | 31 |
2 files changed, 25 insertions, 12 deletions
diff --git a/openstack/common/jsonutils.py b/openstack/common/jsonutils.py index 6130a7f..f96e727 100644 --- a/openstack/common/jsonutils.py +++ b/openstack/common/jsonutils.py @@ -107,9 +107,11 @@ def to_primitive(value, convert_instances=False, level=0): elif hasattr(value, 'iteritems'): return to_primitive(dict(value.iteritems()), convert_instances=convert_instances, - level=level) + level=level + 1) elif hasattr(value, '__iter__'): - return to_primitive(list(value), level) + return to_primitive(list(value), + convert_instances=convert_instances, + level=level) elif convert_instances and hasattr(value, '__dict__'): # Likely an instance of something. Watch for cycles. # Ignore class member vars. diff --git a/tests/unit/test_jsonutils.py b/tests/unit/test_jsonutils.py index 4a18b77..46b5b36 100644 --- a/tests/unit/test_jsonutils.py +++ b/tests/unit/test_jsonutils.py @@ -88,19 +88,30 @@ class ToPrimitiveTestCase(unittest.TestCase): self.data = dict(a=1, b=2, c=3).items() self.index = 0 - def __iter__(self): - return self + def iteritems(self): + return self.data - def next(self): - if self.index == len(self.data): - raise StopIteration - self.index = self.index + 1 - return self.data[self.index - 1] + x = IterItemsClass() + p = jsonutils.to_primitive(x) + self.assertEquals(p, {'a': 1, 'b': 2, 'c': 3}) + + def test_iteritems_with_cycle(self): + class IterItemsClass(object): + def __init__(self): + self.data = dict(a=1, b=2, c=3) + self.index = 0 + + def iteritems(self): + return self.data.items() x = IterItemsClass() - ordered = jsonutils.to_primitive(x) - ordered.sort() - self.assertEquals(ordered, [['a', 1], ['b', 2], ['c', 3]]) + x2 = IterItemsClass() + x.data['other'] = x2 + x2.data['other'] = x + + # If the cycle isn't caught, to_primitive() will eventually result in + # an exception due to excessive recursion depth. + p = jsonutils.to_primitive(x) def test_instance(self): class MysteryClass(object): |
