Skip to content

Commit

Permalink
Fix uiri#217: dumps unable to detect circular refs
Browse files Browse the repository at this point in the history
If an object is passed to dumps, and that object has a circular
reference, then dumps will raise a ValueError because an object with
circular references cannot be encoded as valid TOML.
  • Loading branch information
uiri committed Oct 27, 2018
1 parent 660dd2d commit 7dd67a6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ def test_valid_tests():
toml.dumps(toml.load(open(os.path.join(valid_dir, f))))


def test_circular_ref():
a = {}
b = {}
b['c'] = 4
b['self'] = b
a['b'] = b
with pytest.raises(ValueError):
toml.dumps(a)

with pytest.raises(ValueError):
toml.dumps(b)


def test__dict():
class TestDict(dict):
pass
Expand Down
6 changes: 6 additions & 0 deletions toml/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ def dumps(o, encoder=None):
encoder = TomlEncoder(o.__class__)
addtoretval, sections = encoder.dump_sections(o, "")
retval += addtoretval
outer_objs = [id(o)]
while sections:
section_ids = [id(section) for section in sections]
for outer_obj in outer_objs:
if outer_obj in section_ids:
raise ValueError("Circular reference detected")
outer_objs += section_ids
newsections = encoder.get_empty_table()
for section in sections:
addtoretval, addtosections = encoder.dump_sections(
Expand Down

0 comments on commit 7dd67a6

Please sign in to comment.