ConfigUpdater 4.1__tar.gz → 4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {configupdater-4.1 → configupdater-4.2}/AUTHORS.rst +5 -0
  2. {configupdater-4.1 → configupdater-4.2}/CHANGELOG.rst +63 -0
  3. {configupdater-4.1 → configupdater-4.2}/PKG-INFO +1 -1
  4. {configupdater-4.1 → configupdater-4.2}/src/configupdater/block.py +2 -1
  5. {configupdater-4.1 → configupdater-4.2}/src/configupdater/builder.py +7 -1
  6. {configupdater-4.1 → configupdater-4.2}/src/configupdater/configupdater.py +11 -3
  7. {configupdater-4.1 → configupdater-4.2}/src/configupdater/container.py +21 -1
  8. {configupdater-4.1 → configupdater-4.2}/src/configupdater/document.py +52 -18
  9. {configupdater-4.1 → configupdater-4.2}/src/configupdater/option.py +7 -0
  10. {configupdater-4.1 → configupdater-4.2}/src/configupdater/parser.py +5 -3
  11. {configupdater-4.1 → configupdater-4.2}/src/configupdater/section.py +27 -16
  12. {configupdater-4.1 → configupdater-4.2}/tests/test_configupdater.py +331 -1
  13. {configupdater-4.1 → configupdater-4.2}/tests/test_optionxform.py +74 -1
  14. {configupdater-4.1 → configupdater-4.2}/tests/test_section.py +123 -1
  15. {configupdater-4.1 → configupdater-4.2}/.gitignore +0 -0
  16. {configupdater-4.1 → configupdater-4.2}/CONTRIBUTING.rst +0 -0
  17. {configupdater-4.1 → configupdater-4.2}/LICENSE.txt +0 -0
  18. {configupdater-4.1 → configupdater-4.2}/README.md +0 -0
  19. {configupdater-4.1 → configupdater-4.2}/docs/_static/.gitignore +0 -0
  20. {configupdater-4.1 → configupdater-4.2}/docs/api.rst +0 -0
  21. {configupdater-4.1 → configupdater-4.2}/docs/authors.rst +0 -0
  22. {configupdater-4.1 → configupdater-4.2}/docs/changelog.rst +0 -0
  23. {configupdater-4.1 → configupdater-4.2}/docs/conf.py +0 -0
  24. {configupdater-4.1 → configupdater-4.2}/docs/contributing.rst +0 -0
  25. {configupdater-4.1 → configupdater-4.2}/docs/gfx/README.md +0 -0
  26. {configupdater-4.1 → configupdater-4.2}/docs/gfx/banner-1280x645.png +0 -0
  27. {configupdater-4.1 → configupdater-4.2}/docs/gfx/banner-640x323.png +0 -0
  28. {configupdater-4.1 → configupdater-4.2}/docs/gfx/configupdater.svg +0 -0
  29. {configupdater-4.1 → configupdater-4.2}/docs/gfx/configupdater_plain.svg +0 -0
  30. {configupdater-4.1 → configupdater-4.2}/docs/gfx/favicon.ico +0 -0
  31. {configupdater-4.1 → configupdater-4.2}/docs/gfx/icon-92x128.png +0 -0
  32. {configupdater-4.1 → configupdater-4.2}/docs/gfx/icon.svg +0 -0
  33. {configupdater-4.1 → configupdater-4.2}/docs/gfx/sidebar-254x128.png +0 -0
  34. {configupdater-4.1 → configupdater-4.2}/docs/index.rst +0 -0
  35. {configupdater-4.1 → configupdater-4.2}/docs/license.rst +0 -0
  36. {configupdater-4.1 → configupdater-4.2}/docs/usage.rst +0 -0
  37. {configupdater-4.1 → configupdater-4.2}/pyproject.toml +0 -0
  38. {configupdater-4.1 → configupdater-4.2}/src/configupdater/__init__.py +0 -0
  39. {configupdater-4.1 → configupdater-4.2}/src/configupdater/py.typed +0 -0
  40. {configupdater-4.1 → configupdater-4.2}/tests/conftest.py +0 -0
  41. {configupdater-4.1 → configupdater-4.2}/tests/test_option.py +0 -0
  42. {configupdater-4.1 → configupdater-4.2}/tests/test_parser.py +0 -0
  43. {configupdater-4.1 → configupdater-4.2}/tests/test_readme.py +0 -0
  44. {configupdater-4.1 → configupdater-4.2}/tests/test_setup.cfg +0 -0
  45. {configupdater-4.1 → configupdater-4.2}/tools/__init__.py +0 -0
  46. {configupdater-4.1 → configupdater-4.2}/tools/release_notes.py +0 -0
  47. {configupdater-4.1 → configupdater-4.2}/tools/stdlib_diff.py +0 -0
@@ -12,3 +12,8 @@ Contributors
12
12
  * bysiber (GitHub)
13
13
  * civilwarinfrance (GitHub)
14
14
  * AlexXuz (GitHub)
15
+ * youdie006 (GitHub)
16
+ * jeromeyyy (GitHub)
17
+ * TohruSu (GitHub)
18
+ * anubhavlal07 (GitHub)
19
+ * fbirds5230 (GitHub)
@@ -2,6 +2,69 @@
2
2
  Changelog
3
3
  =========
4
4
 
5
+ Version 4.2
6
+ ===========
7
+
8
+ - Keep existing options and sections intact when assigning a replacement that
9
+ is already attached to another container and raises ``AlreadyAttachedError``,
10
+ PR #189
11
+ - **Behavior change:** Removing an option or section with ``del``, ``pop()``,
12
+ ``popitem()``, ``remove_option()`` or ``remove_section()`` detaches it, as
13
+ ``clear()`` and ``detach()`` already do, so it can be added to another section or
14
+ document instead of raising ``AlreadyAttachedError``. Like any detached block, it
15
+ no longer reaches its former parent: ``Option.key``, ``Option.section``,
16
+ ``Section.document`` and reading or changing the options of a removed section,
17
+ e.g. ``section["key"]``, ``in``, ``get()``, ``set()`` or ``to_dict()``, raise
18
+ ``NotAttachedError`` until it is added again. ``Option.value``,
19
+ ``Option.raw_key`` and ``Section.name`` keep working. A section popped from
20
+ ``ConfigParser`` cannot be read either, so read it before removing it
21
+ (follow-up to PR #180), PR #188
22
+ - **Behavior change:** ``updater[key] = section`` raises a ``ValueError`` if the
23
+ section's name is not ``key`` also when it replaces an existing section, as it
24
+ already did when it adds one. Before, ``updater["a"] = updater["b"]`` put the same
25
+ section twice into the document, and a copied or detached section replaced
26
+ ``[a]`` under its own name, so ``updater["a"]`` was gone afterwards. ConfigParser
27
+ copies the options of ``b`` into ``a`` instead; to do the same, assign a
28
+ ``copy.deepcopy`` of ``b`` renamed to ``a``. The error message now says "section
29
+ name" instead of "option key", PR #191
30
+ - ``update_file()`` encodes the configuration before it opens the file, so a value
31
+ that the file's encoding cannot represent raises ``UnicodeEncodeError`` and leaves
32
+ the file untouched instead of emptying it (follow-up to PR #165), PR #190
33
+ - **Behavior change:** ``items(section)`` raises ``NoSectionError`` instead of
34
+ ``KeyError`` for a missing section, like ``ConfigParser.items()`` and the other
35
+ methods that take a section name, e.g. ``options()``, ``get()`` and ``set()``,
36
+ PR #193
37
+ - Renaming an option by setting ``Option.key`` keeps its original lines and only
38
+ replaces the key, so the continuation lines of a multi-line value stay indented
39
+ instead of turning into new options. A renamed option also keeps its delimiter
40
+ spacing, e.g. ``opt=42`` becomes ``new=42`` instead of ``new = 42``, issue #195
41
+ - ``set()`` leaves the section unchanged when it rejects the value, e.g. a multi-line
42
+ string, or when iterating over the values raises. Before, it had already added the
43
+ new option without a value and could add a newline to the line before it, PR #197
44
+ - **Behavior change:** ``section[key] = value`` and the builder's ``option(key,
45
+ value)`` raise ``AssignMultilineValueError`` for a multi-line string also when they
46
+ create a new option, as assigning it to an existing option already does. Before,
47
+ the string was written as is, which gave an invalid file unless its continuation
48
+ lines were indented. Use ``set(key, lines)`` or ``Option.set_values()`` for a
49
+ multi-line value, PR #202
50
+ - Use the configured ``optionxform`` in ``validate_format()``, ``write()`` and
51
+ ``update_file()``. Case-sensitive options can be saved without false duplicate
52
+ errors, and duplicates introduced by custom normalization are rejected
53
+ (follow-up to PR #69), PR #203
54
+ - **Behavior change:** Reading a section with two options whose keys are equal after
55
+ ``optionxform``, e.g. ``Key`` and ``key`` with the default lowercase
56
+ transformation, raises ``DuplicateOptionError`` like ``ConfigParser``. Before, only
57
+ options with the same spelling were duplicates, so such a file was read, but
58
+ ``write()`` and ``update_file()`` refused to save it. Options keep the spelling of
59
+ their keys as before, PR #204
60
+
61
+ Version 4.1.1
62
+ =============
63
+
64
+ - Insert a newline before blocks added with ``add_after`` or ``insert_at`` when the
65
+ file does not end with one, as ``add_section`` and ``add_option`` already do
66
+ (follow-up to PR #178), PR #185
67
+
5
68
  Version 4.1
6
69
  ===========
7
70
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ConfigUpdater
3
- Version: 4.1
3
+ Version: 4.2
4
4
  Summary: Parser like ConfigParser but for updating configuration files
5
5
  Project-URL: Homepage, https://github.com/pyscaffold/configupdater
6
6
  Project-URL: Documentation, https://configupdater.readthedocs.io/
@@ -55,7 +55,8 @@ class AlreadyAttachedError(Exception):
55
55
 
56
56
 
57
57
  class AssignMultilineValueError(Exception):
58
- """Raised when a multi-line value is assigned to an option's ``value``.
58
+ """Raised when a multi-line value is assigned to an option's ``value`` or given
59
+ to a new option, e.g. with ``section[key] = value``.
59
60
 
60
61
  Use the option's ``set_values`` or ``append`` method for multi-line values.
61
62
  """
@@ -21,6 +21,7 @@ class BlockBuilder:
21
21
  self._idx = idx
22
22
 
23
23
  def _insert(self, block: Block) -> Self:
24
+ self._idx = self._container._ensure_newline_before(self._idx)
24
25
  self._container.structure.insert(self._idx, block)
25
26
  self._idx += 1
26
27
  return self
@@ -103,7 +104,9 @@ class BlockBuilder:
103
104
 
104
105
  Args:
105
106
  key (str): key of the option
106
- value (str or None): value of the option
107
+ value (str or None): value of the option, a single line. Call
108
+ :meth:`~configupdater.Option.set_values` on the new option for a
109
+ multi-line value.
107
110
  delimiter (str or None): delimiter between key and value, by default
108
111
  the first of the ``delimiters`` given to
109
112
  :class:`~configupdater.ConfigUpdater`
@@ -112,6 +115,9 @@ class BlockBuilder:
112
115
 
113
116
  Returns:
114
117
  self for chaining
118
+
119
+ Raises:
120
+ AssignMultilineValueError: if ``value`` is a string with several lines
115
121
  """
116
122
  from .section import Section
117
123
 
@@ -189,7 +189,8 @@ class ConfigUpdater(Document):
189
189
  """Update the read-in configuration file.
190
190
 
191
191
  The file is written with the encoding it was read with, see :meth:`read` and
192
- :meth:`read_file`.
192
+ :meth:`read_file`. Serialization and encoding finish before the file is opened
193
+ for writing, so an encoding error leaves the original file untouched.
193
194
 
194
195
  Args:
195
196
  validate (bool): validate format before writing
@@ -199,8 +200,15 @@ class ConfigUpdater(Document):
199
200
  if validate: # validate BEFORE opening the file!
200
201
  self.validate_format()
201
202
  encoding = io.text_encoding(self._encoding)
202
- with open(self._filename, "w", encoding=encoding) as fb:
203
- self.write(fb, validate=False)
203
+ with (
204
+ io.BytesIO() as buffer,
205
+ io.TextIOWrapper(buffer, encoding=encoding) as stream,
206
+ ):
207
+ self.write(stream, validate=False)
208
+ stream.flush()
209
+ data = buffer.getvalue()
210
+ with open(self._filename, "wb") as fb:
211
+ fb.write(data)
204
212
  return self
205
213
 
206
214
  def validate_format(self, **kwargs: Any) -> bool:
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  from collections.abc import Iterator
11
11
  from copy import deepcopy
12
12
  from textwrap import indent
13
- from typing import TYPE_CHECKING, Any, Generic, Self, TypeVar
13
+ from typing import TYPE_CHECKING, Any, Generic, Self, TypeVar, cast
14
14
 
15
15
  if TYPE_CHECKING:
16
16
  from .block import Block
@@ -75,6 +75,26 @@ class Container(Generic[T]):
75
75
  del self._structure[idx]
76
76
  return self
77
77
 
78
+ def _ensure_newline_before(self, idx: int) -> int:
79
+ """Insert a newline at index idx if the block before it doesn't end with one
80
+
81
+ This happens after the last block of a file without a trailing newline.
82
+ A block inserted there would otherwise be glued onto that line.
83
+
84
+ Returns:
85
+ index where the new block has to be inserted
86
+ """
87
+ from .block import Space
88
+
89
+ idx = min(idx, len(self._structure))
90
+ if idx > 0 and not str(self._structure[idx - 1]).endswith("\n"):
91
+ space = Space(container=self)
92
+ space.add_line("\n")
93
+ # Every container (document and section) holds `Space` blocks
94
+ self._structure.insert(idx, cast(T, space))
95
+ idx += 1
96
+ return idx
97
+
78
98
  def iter_blocks(self) -> Iterator[T]:
79
99
  """Iterate over all blocks inside container."""
80
100
  return iter(self._structure)
@@ -89,7 +89,7 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
89
89
  return optionstr.lower()
90
90
 
91
91
  def validate_format(self, **kwargs: Any) -> bool:
92
- """Call ConfigParser to validate config
92
+ """Call ConfigParser to validate config with this document's optionxform.
93
93
 
94
94
  Args:
95
95
  kwargs: are passed to :class:`configparser.ConfigParser`
@@ -102,6 +102,7 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
102
102
  """
103
103
  kwargs.pop("space_around_delimiters", None)
104
104
  parser = ConfigParser(**kwargs)
105
+ parser.optionxform = self.optionxform # type: ignore[method-assign]
105
106
  parser.read_string(str(self))
106
107
  return True
107
108
 
@@ -139,18 +140,40 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
139
140
  raise KeyError(f"No section `{key}` found", {"key": key})
140
141
 
141
142
  def __setitem__(self, key: str, value: Section) -> None:
143
+ """Add the section ``value`` or replace the existing section ``key`` with it.
144
+
145
+ ``value`` must be a :class:`~configupdater.section.Section` whose name is
146
+ ``key``, and it is inserted itself, not copied. Assigning a section to its
147
+ own key does nothing.
148
+
149
+ This deviates from ConfigParser, where ``parser[key] = value`` copies the
150
+ options of any mapping into the section ``key``, so ``parser["a"] =
151
+ parser["b"]`` gives ``a`` the options of ``b``. Here this raises a
152
+ :class:`ValueError` because the names differ. To copy a section, assign a
153
+ :func:`copy.deepcopy` of it after renaming the copy with
154
+ :attr:`~configupdater.section.Section.name`.
155
+
156
+ Raises:
157
+ ValueError: if ``value`` is not a
158
+ :class:`~configupdater.section.Section` or its name is not ``key``
159
+ AlreadyAttachedError: if ``value`` belongs to another document
160
+ """
142
161
  if not isinstance(value, Section):
143
162
  raise ValueError("Value must be of type Section!")
163
+ # The name check also rejects sections of this document stored under
164
+ # another key, which would otherwise end up twice in ``_structure``.
165
+ if value.name != key:
166
+ raise ValueError(
167
+ f"Set key `{key}` does not equal section name `{value.name}`"
168
+ )
144
169
  if key in self:
145
- idx = self._get_section_idx(key)
146
- self.__getitem__(key).detach()
147
- value.attach(self)
148
- self._structure.insert(idx, value)
170
+ current = self.__getitem__(key)
171
+ if value is not current:
172
+ idx = self._get_section_idx(key)
173
+ value.attach(self)
174
+ current.detach()
175
+ self._structure.insert(idx, value)
149
176
  else:
150
- if value.name != key:
151
- raise ValueError(
152
- f"Set key `{key}` does not equal option key `{value.name}`"
153
- )
154
177
  self.add_section(value)
155
178
 
156
179
  def __delitem__(self, key: str) -> None:
@@ -204,13 +227,7 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
204
227
  if self.has_section(section_obj.name):
205
228
  raise DuplicateSectionError(section_obj.name)
206
229
 
207
- # Ensure a newline before the new section if the last block
208
- # doesn't end with one (e.g. file without trailing newline)
209
- if self._structure and not str(self._structure[-1]).endswith("\n"):
210
- space = Space(container=self)
211
- space.add_line("\n")
212
- self._structure.append(space)
213
-
230
+ self._ensure_newline_before(len(self._structure))
214
231
  section_obj.attach(self)
215
232
  self._structure.append(section_obj)
216
233
 
@@ -327,13 +344,19 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
327
344
  Args:
328
345
  section (str): optional section name, default UNSET
329
346
 
347
+ Raises:
348
+ :class:`NoSectionError`: if ``section`` is given and cannot be found
349
+
330
350
  Returns:
331
351
  list: list of (name, :class:`Section`) or (name, :class:`Option`) tuples
332
352
  """
333
353
  if section is _UNSET:
334
354
  return [(sect.name, sect) for sect in self.iter_sections()]
335
355
 
336
- section_obj = self.__getitem__(section)
356
+ try:
357
+ section_obj = self.__getitem__(section)
358
+ except KeyError:
359
+ raise NoSectionError(section) from None
337
360
  return [(opt.key, opt) for opt in section_obj.iter_options()]
338
361
 
339
362
  def has_option(self, section: str, option: str) -> bool:
@@ -376,6 +399,12 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
376
399
  def remove_option(self, section: str, option: str) -> bool:
377
400
  """Remove an option.
378
401
 
402
+ The removed option is :meth:`detached <configupdater.block.Block.detach>`,
403
+ as with ``del section[option]`` or ``section.pop(option)``, so it can be
404
+ added to another section. Until then, its
405
+ :attr:`~configupdater.option.Option.key` raises
406
+ :obj:`~configupdater.block.NotAttachedError`.
407
+
379
408
  Args:
380
409
  section (str): section name
381
410
  option (str): option name
@@ -396,6 +425,11 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
396
425
  def remove_section(self, name: str) -> bool:
397
426
  """Remove a file section.
398
427
 
428
+ The removed section is :meth:`detached <configupdater.block.Block.detach>`,
429
+ as with ``del document[name]`` or ``document.pop(name)``, so it can be
430
+ added to another document. Until then, accessing its options raises
431
+ :obj:`~configupdater.block.NotAttachedError`.
432
+
399
433
  Args:
400
434
  name: name of the section
401
435
 
@@ -404,7 +438,7 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
404
438
  """
405
439
  try:
406
440
  idx = self._get_section_idx(name)
407
- del self._structure[idx]
441
+ self._structure[idx].detach()
408
442
  return True
409
443
  except StopIteration:
410
444
  return False
@@ -173,6 +173,13 @@ class Option(Block):
173
173
 
174
174
  @key.setter
175
175
  def key(self, value: str) -> None:
176
+ if self._lines and not self._updated:
177
+ first = self._lines[0]
178
+ start = first.find(self._key)
179
+ end = start + len(self._key)
180
+ self._lines[0] = f"{first[:start]}{value}{first[end:]}"
181
+ self._key = value
182
+ return
176
183
  self._join_multiline_value()
177
184
  self._key = value
178
185
  self._updated = True
@@ -516,10 +516,12 @@ class Parser:
516
516
  if sectname is None: # pragma: no cover
517
517
  msg = f"Could not find the section name for {optname}"
518
518
  raise InconsistentStateError(msg, fpname, lineno, line)
519
- if self._strict and (sectname, optname) in elements_added:
520
- args = (sectname, optname, fpname, lineno)
519
+ # but find duplicates by the transformed key like ConfigParser
520
+ optkey = self.optionxform(optname)
521
+ if self._strict and (sectname, optkey) in elements_added:
522
+ args = (sectname, optkey, fpname, lineno)
521
523
  raise DuplicateOptionError(*args)
522
- elements_added.add((sectname, optname))
524
+ elements_added.add((sectname, optkey))
523
525
  # This check is fine because the OPTCRE cannot
524
526
  # match if it would set optval to None
525
527
  if optval is not None:
@@ -20,10 +20,10 @@ from typing import TYPE_CHECKING, Any, Self, TypeVar, cast, overload
20
20
  if TYPE_CHECKING:
21
21
  from .document import Document
22
22
 
23
- from .block import Block, Comment, Space
23
+ from .block import AssignMultilineValueError, Block, Comment, Space
24
24
  from .builder import BlockBuilder
25
25
  from .container import Container
26
- from .option import Option
26
+ from .option import Option, is_multi_line
27
27
 
28
28
  T = TypeVar("T")
29
29
 
@@ -71,14 +71,7 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
71
71
  entry (Option): key value pair as Option object
72
72
  """
73
73
  entry.attach(self)
74
-
75
- # Ensure a newline before the new option if the last block
76
- # doesn't end with one (e.g. file without trailing newline)
77
- if self._structure and not str(self._structure[-1]).endswith("\n"):
78
- space = Space(container=self)
79
- space.add_line("\n")
80
- self._structure.append(space)
81
-
74
+ self._ensure_newline_before(len(self._structure))
82
75
  self._structure.append(entry)
83
76
  return self
84
77
 
@@ -168,6 +161,14 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
168
161
  :meth:`~configupdater.document.Document.optionxform` to verify if the given
169
162
  option already exists inside the section object. A new option keeps the
170
163
  given ``key`` as :attr:`~configupdater.Option.raw_key`.
164
+
165
+ Unlike :class:`~configparser.ConfigParser`, a string ``value`` must be a
166
+ single line, for a new option as for an existing one. Pass a list of lines to
167
+ :meth:`set` or use :meth:`Option.set_values() <configupdater.Option.set_values>`
168
+ for a multi-line value.
169
+
170
+ Raises:
171
+ AssignMultilineValueError: if ``value`` is a string with several lines
171
172
  """
172
173
  # First we check for inconsistencies
173
174
  given_key = self.document.optionxform(key)
@@ -186,10 +187,11 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
186
187
  curr_option = self._find_option(given_key)
187
188
  if curr_option is not None: # Replace an existing option
188
189
  if isinstance(value, Option):
189
- idx = curr_option.container_idx
190
- curr_option.detach()
191
- value.attach(self)
192
- self._structure.insert(idx, value)
190
+ if value is not curr_option:
191
+ idx = curr_option.container_idx
192
+ value.attach(self)
193
+ curr_option.detach()
194
+ self._structure.insert(idx, value)
193
195
  else:
194
196
  curr_option.value = value
195
197
  else: # Append a new option
@@ -199,7 +201,7 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
199
201
  key = self.document.optionxform(key)
200
202
  try:
201
203
  idx = self._get_option_idx(key=key)
202
- del self._structure[idx]
204
+ self._structure[idx].detach()
203
205
  except StopIteration as ex:
204
206
  raise KeyError(f"No option `{key}` found", {"key": key}) from ex
205
207
 
@@ -295,13 +297,15 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
295
297
  value: value, default None
296
298
  """
297
299
  opt = self._find_option(self.document.optionxform(option))
300
+ is_new = opt is None
298
301
  if opt is None:
299
302
  opt = self.create_option(option)
300
- self.add_option(opt)
301
303
  if not isinstance(value, Iterable) or isinstance(value, str):
302
304
  opt.value = value
303
305
  else:
304
306
  opt.set_values(value)
307
+ if is_new:
308
+ self.add_option(opt)
305
309
  return self
306
310
 
307
311
  def create_option(
@@ -322,7 +326,14 @@ class Section(Block, Container[Content], MutableMapping[str, Option]):
322
326
  Warning:
323
327
  This is a low level API, not intended for public use.
324
328
  Prefer :meth:`set` or :meth:`__setitem__`.
329
+
330
+ Raises:
331
+ AssignMultilineValueError: if ``value`` is a string with several lines,
332
+ as when it is assigned to :attr:`Option.value
333
+ <configupdater.Option.value>`
325
334
  """
335
+ if is_multi_line(value):
336
+ raise AssignMultilineValueError(Option(key))
326
337
  syntax_opts = getattr(self._container, "syntax_options", {})
327
338
  if delimiter is None:
328
339
  delimiter = next(iter(syntax_opts.get("delimiters", [])), None)
@@ -72,6 +72,32 @@ def test_clear_detaches_all_document_blocks(config, reload):
72
72
  assert other.to_dict() == original_values
73
73
 
74
74
 
75
+ @pytest.mark.parametrize("method", ["del", "pop", "remove_section"])
76
+ def test_removed_section_is_detached(method):
77
+ config = "[one]\nkey = 1\n[two]\nkey = 2\n"
78
+ updater = ConfigUpdater().read_string(config)
79
+ section = updater["one"]
80
+ reference = ConfigParser()
81
+ reference.read_string(config)
82
+ reference.remove_section("one")
83
+
84
+ if method == "del":
85
+ del updater["one"]
86
+ elif method == "pop":
87
+ assert updater.pop("one") is section
88
+ else:
89
+ assert updater.remove_section("one") is True
90
+
91
+ assert not section.has_container()
92
+ assert updater.sections() == reference.sections() == ["two"]
93
+ assert str(updater) == "[two]\nkey = 2\n"
94
+ assert all(option.container is section for option in section.iter_options())
95
+ other = ConfigUpdater()
96
+ other.add_section(section)
97
+ assert section.container is other
98
+ assert other.to_dict() == {"one": {"key": "1"}}
99
+
100
+
75
101
  def test_read_file_like(setup_cfg_path):
76
102
  updater = ConfigUpdater()
77
103
  with open(setup_cfg_path) as fp:
@@ -203,6 +229,67 @@ def test_update_file_after_read_string_keeps_file_and_encoding(tmp_path):
203
229
  assert file.read_text(encoding="utf-16") == NON_ASCII_UPDATED
204
230
 
205
231
 
232
+ @pytest.mark.parametrize("encoding", ["ascii", "latin-1"])
233
+ @pytest.mark.parametrize("read_method", ["read", "read_file"])
234
+ @pytest.mark.parametrize("validate", [False, True])
235
+ def test_update_file_preserves_original_on_encoding_error(
236
+ tmp_path, encoding, read_method, validate
237
+ ):
238
+ file = tmp_path / "file.cfg"
239
+ original = b"# keep this comment\n[section]\nkey = original\n"
240
+ file.write_bytes(original)
241
+ updater = ConfigUpdater()
242
+ if read_method == "read":
243
+ updater.read(file, encoding=encoding)
244
+ else:
245
+ with file.open(encoding=encoding) as stream:
246
+ updater.read_file(stream)
247
+ updater["section"]["key"] = "snowman: \u2603"
248
+
249
+ with pytest.raises(UnicodeEncodeError, match="can't encode"):
250
+ updater.update_file(validate=validate)
251
+
252
+ assert file.read_bytes() == original
253
+ updater["section"]["key"] = "recovered"
254
+ assert updater.update_file(validate=validate) is updater
255
+ assert file.read_text(encoding=encoding) == original.decode().replace(
256
+ "key = original", "key = recovered"
257
+ )
258
+
259
+
260
+ def test_update_file_preserves_original_when_custom_write_fails(tmp_path):
261
+ class FailingWriter(ConfigUpdater):
262
+ def write(self, fp, validate=True):
263
+ super().write(fp, validate=validate)
264
+ raise RuntimeError("serialization interrupted")
265
+
266
+ file = tmp_path / "file.cfg"
267
+ original = b"[section]\nkey = original\n"
268
+ file.write_bytes(original)
269
+ updater = FailingWriter().read(file, encoding="utf-8")
270
+ updater["section"]["key"] = "changed"
271
+
272
+ with pytest.raises(RuntimeError, match="serialization interrupted"):
273
+ updater.update_file()
274
+
275
+ assert file.read_bytes() == original
276
+
277
+
278
+ @pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig", "utf-16", "utf-32"])
279
+ def test_update_file_preserves_encoding_and_bom(tmp_path, encoding):
280
+ file = tmp_path / "file.cfg"
281
+ text = "# keep this comment\n[section]\nkey = original\n"
282
+ file.write_text(text, encoding=encoding)
283
+ updater = ConfigUpdater().read(file, encoding=encoding)
284
+ updater["section"]["key"] = "snowman: \u2603"
285
+ expected = text.replace("key = original", "key = snowman: \u2603")
286
+
287
+ assert updater.update_file() is updater
288
+
289
+ assert file.read_bytes() == expected.replace("\n", os.linesep).encode(encoding)
290
+ assert ConfigUpdater().read(file, encoding=encoding).to_dict() == updater.to_dict()
291
+
292
+
206
293
  def test_encoding_warning_points_to_caller(tmp_path):
207
294
  # `-X warn_default_encoding` (PEP 597) cannot be enabled in a running interpreter
208
295
  file = tmp_path / "file.cfg"
@@ -424,6 +511,17 @@ def test_items(setup_cfg_path):
424
511
  assert all(isinstance(o, Option) for o in opts)
425
512
 
426
513
 
514
+ def test_items_of_missing_section():
515
+ config = "[section]\nkey = value\n"
516
+ parser = ConfigParser()
517
+ parser.read_string(config)
518
+ with pytest.raises(NoSectionError, match="No section: 'missing'"):
519
+ parser.items("missing")
520
+ updater = ConfigUpdater().read_string(config)
521
+ with pytest.raises(NoSectionError, match="No section: 'missing'"):
522
+ updater.items("missing")
523
+
524
+
427
525
  def test_get_method(setup_cfg_path):
428
526
  updater = ConfigUpdater()
429
527
  updater.read(setup_cfg_path)
@@ -811,6 +909,56 @@ def test_add_section_no_trailing_newline():
811
909
  assert "value2[section2]" not in result
812
910
 
813
911
 
912
+ @pytest.mark.parametrize("newline", ["\n", "\r\n"])
913
+ @pytest.mark.parametrize(
914
+ "body", ["", "{nl}key : value", "{nl}# tail", "{nl}key = one{nl} two"]
915
+ )
916
+ @pytest.mark.parametrize(
917
+ ("method", "added"),
918
+ [
919
+ ("option", "new_key = v\n"),
920
+ ("comment", "# note\n"),
921
+ ("space", "\n"),
922
+ ("section", "[t]\n"),
923
+ ],
924
+ )
925
+ def test_builder_no_trailing_newline(newline, body, method, added):
926
+ original = "[s]" + body.format(nl=newline)
927
+ updater = ConfigUpdater().read_string(original)
928
+ expected = ConfigParser(interpolation=None)
929
+ expected.read_string(original)
930
+ section = updater["s"]
931
+ builder = section.insert_at(len(section.structure))
932
+ if method == "option":
933
+ builder.option("new_key", "v")
934
+ expected.set("s", "new_key", "v")
935
+ elif method == "comment":
936
+ builder.comment("note")
937
+ elif method == "space":
938
+ builder.space()
939
+ else:
940
+ section.add_after.section("t")
941
+ expected.add_section("t")
942
+ assert str(updater) == original + "\n" + added
943
+ parser = ConfigParser(interpolation=None)
944
+ parser.read_string(str(updater))
945
+ assert {s: dict(parser[s]) for s in parser} == {
946
+ s: dict(expected[s]) for s in expected
947
+ }
948
+
949
+
950
+ def test_builder_insert_at_start_no_trailing_newline():
951
+ updater = ConfigUpdater().read_string("[s]\nkey = v")
952
+ updater["s"].insert_at(0).option("first", "1")
953
+ assert str(updater) == "[s]\nfirst = 1\nkey = v"
954
+
955
+
956
+ def test_builder_insert_past_end_no_trailing_newline():
957
+ updater = ConfigUpdater().read_string("[s]\nkey = v")
958
+ updater["s"].insert_at(10).option("new", "1").comment("note")
959
+ assert str(updater) == "[s]\nkey = v\nnew = 1\n# note\n"
960
+
961
+
814
962
  test6_cfg_out_overwritten = """
815
963
  [section0]
816
964
  key0 = 42
@@ -828,7 +976,7 @@ def test_set_item_section():
828
976
  updater["section"] = "newsection"
829
977
  sect_updater.read_string(test6_cfg_in)
830
978
  section = sect_updater["section0"]
831
- with pytest.raises(ValueError, match="does not equal option key"):
979
+ with pytest.raises(ValueError, match="does not equal section name"):
832
980
  updater["new_section"] = section
833
981
  section.name = "new_section"
834
982
  updater["new_section"] = section.detach()
@@ -904,6 +1052,34 @@ def test_duplicate_option_error():
904
1052
  updater.read_string(test10_dup_option)
905
1053
 
906
1054
 
1055
+ @pytest.mark.parametrize(
1056
+ ("optionxform", "config"),
1057
+ [
1058
+ (str.lower, "[section]\nKey = 1\nkey = 2\n"),
1059
+ (lambda key: key.replace("_", ""), "[section]\nkey = 1\nk_e_y = 2\n"),
1060
+ ],
1061
+ ids=["default", "custom"],
1062
+ )
1063
+ def test_duplicate_option_error_after_optionxform(optionxform, config):
1064
+ # Like ConfigParser, options are duplicates if their transformed keys are equal
1065
+ match = "option 'key' in section 'section' already exists"
1066
+ parser = ConfigParser()
1067
+ parser.optionxform = optionxform
1068
+ with pytest.raises(DuplicateOptionError, match=match):
1069
+ parser.read_string(config)
1070
+ updater = ConfigUpdater()
1071
+ updater.optionxform = optionxform
1072
+ with pytest.raises(DuplicateOptionError, match=match):
1073
+ updater.read_string(config)
1074
+
1075
+ # Keys that differ after optionxform are distinct options and keep their spelling
1076
+ updater = ConfigUpdater()
1077
+ updater.optionxform = str
1078
+ updater.read_string(config)
1079
+ assert len(updater["section"]) == 2
1080
+ assert str(updater) == config
1081
+
1082
+
907
1083
  test11_no_values = """
908
1084
  [section]
909
1085
  key
@@ -947,6 +1123,44 @@ def test_rename_option_key():
947
1123
  updater["section"]["option"].key = "option"
948
1124
 
949
1125
 
1126
+ def test_rename_multiline_option_key_issue_195():
1127
+ cfg = dedent(
1128
+ """\
1129
+ [testenv]
1130
+ setenv =
1131
+ TZ = UTC
1132
+ APP_ENV = test
1133
+ deps =
1134
+ pytest
1135
+ coverage
1136
+ """
1137
+ )
1138
+ updater = ConfigUpdater()
1139
+ updater.read_string(cfg)
1140
+ updater["testenv"]["setenv"].key = "set_env"
1141
+ updater["testenv"]["deps"].key = "dependencies"
1142
+ expected = cfg.replace("setenv =", "set_env =").replace("deps =", "dependencies =")
1143
+ assert str(updater) == expected
1144
+ updater.validate_format()
1145
+ parser = ConfigParser()
1146
+ parser.read_string(str(updater))
1147
+ assert parser.options("testenv") == ["set_env", "dependencies"]
1148
+ assert parser["testenv"]["set_env"] == "\nTZ = UTC\nAPP_ENV = test"
1149
+ assert updater["testenv"]["set_env"].value == parser["testenv"]["set_env"]
1150
+
1151
+
1152
+ def test_rename_option_key_keeps_delimiter_spacing_issue_195():
1153
+ updater = ConfigUpdater()
1154
+ updater.read_string("[section]\nOption=42\n")
1155
+ option = updater["section"]["option"]
1156
+ option.key = "renamed"
1157
+ assert str(updater) == "[section]\nrenamed=42\n"
1158
+ assert option.key == "renamed"
1159
+ assert option.value == "42"
1160
+ option.value = "43"
1161
+ assert str(updater) == "[section]\nrenamed = 43\n"
1162
+
1163
+
950
1164
  test13_cfg_in = """
951
1165
  [section]
952
1166
  CAPITAL = 1
@@ -1557,6 +1771,39 @@ def test_modify_multiline_value():
1557
1771
  assert str(updater) == dedent(expected)
1558
1772
 
1559
1773
 
1774
+ def test_new_option_rejects_multi_line_value():
1775
+ original = "[section]\nexisting = 1"
1776
+ updater = ConfigUpdater()
1777
+ updater.read_string(original)
1778
+ section = updater["section"]
1779
+ existing = section["existing"]
1780
+ match = "multi-line value to <Option 'new'>"
1781
+
1782
+ # Like assigning to an existing option, which raises already
1783
+ with pytest.raises(AssignMultilineValueError, match="<Option 'existing'>"):
1784
+ section["existing"] = "one\ntwo"
1785
+ with pytest.raises(AssignMultilineValueError, match=match):
1786
+ section["new"] = "one\ntwo"
1787
+ # Also with indented lines, which happened to give a valid file
1788
+ with pytest.raises(AssignMultilineValueError, match=match):
1789
+ section["new"] = "\n one\n two"
1790
+ with pytest.raises(AssignMultilineValueError, match=match):
1791
+ existing.add_after.option("new", "one\ntwo")
1792
+ with pytest.raises(AssignMultilineValueError, match=match):
1793
+ existing.add_before.option("new", "one\ntwo")
1794
+ with pytest.raises(AssignMultilineValueError, match=match):
1795
+ section.insert_at(0).option("new", "one\ntwo")
1796
+ assert str(updater) == original
1797
+
1798
+ section.set("new", ["one", "two"])
1799
+ assert str(updater) == "[section]\nexisting = 1\nnew =\n one\n two\n"
1800
+ parser = ConfigParser()
1801
+ parser.read_string(str(updater))
1802
+ reread = ConfigUpdater()
1803
+ reread.read_string(str(updater))
1804
+ assert reread["section"]["new"].value == parser["section"]["new"] == "\none\ntwo"
1805
+
1806
+
1560
1807
  def test_append_to_multi_line_value():
1561
1808
  cfg = """\
1562
1809
  [metadata]
@@ -1892,3 +2139,86 @@ def test_none_value_disallowed_message_without_docstrings():
1892
2139
  code = "configupdater.NoneValueDisallowed.warn('key')"
1893
2140
  message = _message_under_python_OO(NoneValueDisallowed, code)
1894
2141
  assert message == str(record[0].message)
2142
+
2143
+
2144
+ def test_replacing_with_attached_section_keeps_existing_section():
2145
+ updater = ConfigUpdater().read_string("[s]\nkey : original\n")
2146
+ source = ConfigUpdater().read_string("[s]\nkey = other\n")
2147
+ section = source["s"]
2148
+ original_section = updater["s"]
2149
+ original = str(updater)
2150
+ original_source = str(source)
2151
+
2152
+ with pytest.raises(AlreadyAttachedError, match="already attached"):
2153
+ updater["s"] = section
2154
+
2155
+ assert str(updater) == original
2156
+ assert str(source) == original_source
2157
+ assert updater["s"] is original_section
2158
+ assert original_section.container is updater
2159
+ assert section.container is source
2160
+
2161
+
2162
+ def test_replacing_section_with_itself_keeps_parent():
2163
+ updater = ConfigUpdater().read_string("[s]\nkey : original\n")
2164
+ section = updater["s"]
2165
+ original = str(updater)
2166
+
2167
+ updater["s"] = section
2168
+
2169
+ assert str(updater) == original
2170
+ assert updater["s"] is section
2171
+ assert section.container is updater
2172
+ assert section.container_idx == 0
2173
+
2174
+
2175
+ @pytest.mark.parametrize(
2176
+ "make_value",
2177
+ [
2178
+ pytest.param(lambda updater: updater["t"], id="same-document"),
2179
+ pytest.param(lambda updater: copy.deepcopy(updater["t"]), id="deepcopy"),
2180
+ pytest.param(lambda updater: Section("t"), id="detached-existing-name"),
2181
+ pytest.param(lambda updater: Section("x"), id="detached-new-name"),
2182
+ ],
2183
+ )
2184
+ def test_replacing_section_with_differently_named_section(make_value):
2185
+ # Without a name check, `updater["s"] = updater["t"]` put the same section twice
2186
+ # into the document (`[t]` twice, no `[s]`) and the deepcopy did the same by name
2187
+ cfg = "[s]\nk = 1\n[t]\nk = 2\n"
2188
+ updater = ConfigUpdater().read_string(cfg)
2189
+ blocks = list(updater.iter_blocks())
2190
+ value = make_value(updater)
2191
+ was_attached = any(block is value for block in blocks)
2192
+
2193
+ with pytest.raises(ValueError, match=f"does not equal section name `{value.name}`"):
2194
+ updater["s"] = value
2195
+
2196
+ assert str(updater) == cfg
2197
+ assert updater.sections() == ["s", "t"]
2198
+ assert len(updater.structure) == len(blocks)
2199
+ assert all(a is b for a, b in zip(updater.structure, blocks, strict=True))
2200
+ assert all(block.container is updater for block in blocks)
2201
+ assert value.has_container() is was_attached
2202
+ assert updater.validate_format()
2203
+
2204
+
2205
+ def test_replacing_section_with_copy_of_another_section_like_configparser():
2206
+ # ConfigParser copies the options of `t` into `s`. A ConfigUpdater section can
2207
+ # only be in one place, so the equivalent is assigning a renamed deepcopy
2208
+ cfg = "[s]\nk = 1\n[t]\nk = 2\nx = 3\n"
2209
+ parser = ConfigParser()
2210
+ parser.read_string(cfg)
2211
+ parser["s"] = parser["t"]
2212
+
2213
+ updater = ConfigUpdater().read_string(cfg)
2214
+ original_t = updater["t"]
2215
+ copied = copy.deepcopy(original_t)
2216
+ copied.name = "s"
2217
+ updater["s"] = copied
2218
+
2219
+ assert updater.to_dict() == {s: dict(parser[s]) for s in parser.sections()}
2220
+ assert str(updater) == "[s]\nk = 2\nx = 3\n[t]\nk = 2\nx = 3\n"
2221
+ assert updater["s"] is copied
2222
+ assert updater["t"] is original_t
2223
+ assert copied.container is updater
2224
+ assert updater.validate_format()
@@ -1,4 +1,5 @@
1
- from configparser import ConfigParser
1
+ from configparser import ConfigParser, DuplicateOptionError
2
+ from io import StringIO
2
3
  from textwrap import dedent
3
4
 
4
5
  import pytest
@@ -48,6 +49,78 @@ def test_custom():
48
49
  assert custom["section1"]["key"].raw_key == "k_e_y"
49
50
 
50
51
 
52
+ def test_validate_format_uses_optionxform():
53
+ config = "[section]\nKey = first\nkey = second\n"
54
+ updater = ConfigUpdater()
55
+ updater.optionxform = str
56
+ updater.read_string(config)
57
+ parser = ConfigParser()
58
+ parser.optionxform = str
59
+ parser.read_string(config)
60
+
61
+ assert updater.validate_format() is True
62
+ assert updater.to_dict() == {"section": dict(parser["section"])}
63
+ assert str(updater) == config
64
+
65
+
66
+ def test_write_uses_optionxform():
67
+ config = "[section]\nKey = first\nkey = second\n"
68
+ updater = ConfigUpdater()
69
+ updater.optionxform = str
70
+ updater.read_string(config)
71
+ output = StringIO()
72
+
73
+ updater.write(output)
74
+
75
+ assert output.getvalue() == config
76
+ parser = ConfigParser()
77
+ parser.optionxform = str
78
+ parser.read_string(output.getvalue())
79
+ assert dict(parser["section"]) == {"Key": "first", "key": "second"}
80
+
81
+
82
+ def test_update_file_uses_optionxform(tmp_path):
83
+ path = tmp_path / "settings.ini"
84
+ path.write_text("[section]\nKey = first\nkey = second\n", encoding="utf-8")
85
+ updater = ConfigUpdater()
86
+ updater.optionxform = str
87
+ updater.read(path, encoding="utf-8")
88
+ updater["section"]["Key"].value = "updated"
89
+
90
+ assert updater.update_file() is updater
91
+
92
+ assert path.read_text(encoding="utf-8") == (
93
+ "[section]\nKey = updated\nkey = second\n"
94
+ )
95
+ parser = ConfigParser()
96
+ parser.optionxform = str
97
+ parser.read(path, encoding="utf-8")
98
+ assert dict(parser["section"]) == {"Key": "updated", "key": "second"}
99
+
100
+
101
+ @pytest.mark.parametrize(
102
+ ("optionxform", "other_key"),
103
+ [(str.lower, "KEY"), (lambda key: key.replace("_", ""), "k_e_y")],
104
+ ids=["default", "custom"],
105
+ )
106
+ def test_validate_format_rejects_normalized_duplicates(optionxform, other_key):
107
+ config = f"[section]\nkey = first\n{other_key} = second\n"
108
+ updater = ConfigUpdater()
109
+ updater.optionxform = str
110
+ updater.read_string(config)
111
+ updater.optionxform = optionxform
112
+ parser = ConfigParser()
113
+ parser.optionxform = optionxform
114
+
115
+ with pytest.raises(DuplicateOptionError, match="option 'key'"):
116
+ parser.read_string(config)
117
+ with pytest.raises(DuplicateOptionError, match="option 'key'"):
118
+ updater.validate_format()
119
+
120
+ assert updater.validate_format(strict=False) is True
121
+ assert str(updater) == config
122
+
123
+
51
124
  def test_section_contains():
52
125
  config = """\
53
126
  [section1]
@@ -5,7 +5,11 @@ from textwrap import dedent
5
5
  import pytest
6
6
 
7
7
  from configupdater import ConfigUpdater
8
- from configupdater.block import AlreadyAttachedError, NotAttachedError
8
+ from configupdater.block import (
9
+ AlreadyAttachedError,
10
+ AssignMultilineValueError,
11
+ NotAttachedError,
12
+ )
9
13
  from configupdater.parser import Parser
10
14
 
11
15
 
@@ -42,6 +46,32 @@ def test_clear_detaches_all_section_blocks(body):
42
46
  assert other["target"].to_dict() == original_values
43
47
 
44
48
 
49
+ @pytest.mark.parametrize("method", ["del", "pop", "remove_option"])
50
+ def test_removed_option_is_detached(method):
51
+ config = "[source]\na = 1\nb = 2\n[target]\n"
52
+ updater = ConfigUpdater().read_string(config)
53
+ source = updater["source"]
54
+ option = source["a"]
55
+ reference = ConfigParser()
56
+ reference.read_string(config)
57
+ reference.remove_option("source", "a")
58
+
59
+ if method == "del":
60
+ del source["a"]
61
+ elif method == "pop":
62
+ assert source.pop("a") is option
63
+ else:
64
+ assert updater.remove_option("source", "a") is True
65
+
66
+ assert not option.has_container()
67
+ assert source.options() == list(reference["source"]) == ["b"]
68
+ assert str(updater) == "[source]\nb = 2\n[target]\n"
69
+ updater["target"]["a"] = option
70
+ assert option.container is updater["target"]
71
+ assert str(updater) == "[source]\nb = 2\n[target]\na = 1\n"
72
+ updater.validate_format()
73
+
74
+
45
75
  def test_add_before_skip_comments():
46
76
  doc = Parser().read_string("[first]\na = 1\n")
47
77
  doc["first"].add_after.space().comment("target comment").section("target")
@@ -126,6 +156,39 @@ def test_set():
126
156
  assert section["testing"].value == "\n pyscaffoldext-markdown\n rst-to-myst"
127
157
 
128
158
 
159
+ def test_set_does_not_insert_option_when_multiline_string_is_rejected():
160
+ original = "[section]\nexisting = 1"
161
+ doc = ConfigUpdater().read_string(original)
162
+ section = doc["section"]
163
+
164
+ with pytest.raises(AssignMultilineValueError, match="multi-line value"):
165
+ section.set("new", "one\ntwo")
166
+
167
+ assert section.options() == ["existing"]
168
+ assert str(doc) == original
169
+ assert section.set("new", ["one", "two"]) is section
170
+ assert ConfigUpdater().read_string(str(doc))["section"]["new"].as_list() == [
171
+ "one",
172
+ "two",
173
+ ]
174
+
175
+
176
+ def test_set_does_not_insert_option_when_value_iterator_fails():
177
+ original = "[section]\nexisting = 1"
178
+ doc = ConfigUpdater().read_string(original)
179
+ section = doc["section"]
180
+
181
+ def values():
182
+ yield "one"
183
+ raise RuntimeError("value iterator failed")
184
+
185
+ with pytest.raises(RuntimeError, match="value iterator failed"):
186
+ section.set("new", values())
187
+
188
+ assert section.options() == ["existing"]
189
+ assert str(doc) == original
190
+
191
+
129
192
  def test_deepcopy():
130
193
  example = """\
131
194
  [options.extras_require]
@@ -272,3 +335,62 @@ def test_append_detached_option_without_trailing_newline(copy_option):
272
335
  assert updater["s"]["new_key"] is option
273
336
  assert option.container is updater["s"]
274
337
  assert str(updater) == "[s]\nkey : value\nnew_key = v"
338
+
339
+
340
+ @pytest.mark.parametrize("source_document", [False, True])
341
+ def test_replacing_with_attached_option_keeps_existing_option(source_document):
342
+ updater = ConfigUpdater().read_string("[s]\nkey : original\n[other]\nkey = other\n")
343
+ source = (
344
+ ConfigUpdater().read_string("[other]\nkey = other\n")
345
+ if source_document
346
+ else updater
347
+ )
348
+ section = updater["s"]
349
+ original_option = section["key"]
350
+ option = source["other"]["key"]
351
+ original = str(updater)
352
+ original_source = str(source)
353
+ blocks = tuple(section.structure)
354
+
355
+ with pytest.raises(AlreadyAttachedError, match="already attached"):
356
+ section["key"] = option
357
+
358
+ assert str(updater) == original
359
+ assert str(source) == original_source
360
+ assert section["key"] is original_option
361
+ assert original_option.container is section
362
+ assert option.container is source["other"]
363
+ assert len(section.structure) == len(blocks)
364
+ assert all(a is b for a, b in zip(section.structure, blocks, strict=True))
365
+
366
+
367
+ def test_replacing_option_with_itself_keeps_parent():
368
+ updater = ConfigUpdater().read_string("[s]\nkey : original\n")
369
+ section = updater["s"]
370
+ option = section["key"]
371
+ original = str(updater)
372
+
373
+ section["key"] = option
374
+
375
+ assert str(updater) == original
376
+ assert section["key"] is option
377
+ assert option.container is section
378
+ assert option.container_idx == 0
379
+
380
+
381
+ def test_replacing_option_with_another_option_of_same_section():
382
+ # Unlike `Document.__setitem__`, the key check already prevented the option from
383
+ # ending up twice in the section
384
+ cfg = "[s]\na = 1\nb = 2\n"
385
+ updater = ConfigUpdater().read_string(cfg)
386
+ section = updater["s"]
387
+ blocks = tuple(section.structure)
388
+
389
+ with pytest.raises(ValueError, match="does not equal option key `b`"):
390
+ section["a"] = section["b"]
391
+
392
+ assert str(updater) == cfg
393
+ assert section.options() == ["a", "b"]
394
+ assert len(section.structure) == len(blocks)
395
+ assert all(a is b for a, b in zip(section.structure, blocks, strict=True))
396
+ assert all(block.container is section for block in blocks)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes