From 953fd3be54b95adaa4f07b5bfb58a480c80023c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Eustace?= Date: Wed, 19 May 2021 18:59:34 +0200 Subject: [PATCH] Fix top level keys handling when building --- tests/test_build.py | 18 ++++++++++++++++++ tomlkit/container.py | 4 +--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/test_build.py b/tests/test_build.py index 078eba9a..098b2d52 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -79,6 +79,7 @@ def test_build_example(example): doc.add(nl()) doc.add(comment("Products")) + doc.add(nl()) products = aot() doc["products"] = products @@ -128,3 +129,20 @@ def test_append_table_after_multiple_indices(): """ doc = parse(content) doc.append("foobar", {"name": "John"}) + + +def test_top_level_keys_are_put_at_the_root_of_the_document(): + doc = document() + doc.add(comment("Comment")) + doc["foo"] = {"name": "test"} + doc["bar"] = 1 + + expected = """\ +# Comment +bar = 1 + +[foo] +name = "test" +""" + + assert doc.as_string() diff --git a/tomlkit/container.py b/tomlkit/container.py index 41aa707a..4e3ea12a 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -112,8 +112,6 @@ def append(self, key, item): # type: (Union[Key, str, None], Item) -> Container if isinstance(item, AoT) and self._body and not self._parsed: if item and "\n" not in item[0].trivia.indent: item[0].trivia.indent = "\n" + item[0].trivia.indent - else: - self.append(None, Whitespace("\n")) if key is not None and key in self: current_idx = self._map[key] @@ -211,7 +209,7 @@ def append(self, key, item): # type: (Union[Key, str, None], Item) -> Container if key_after is not None: if isinstance(key_after, int): - if key_after + 1 < len(self._body) - 1: + if key_after + 1 < len(self._body): return self._insert_at(key_after + 1, key, item) else: previous_item = self._body[-1][1]