test_config.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. # test_config.py -- Tests for reading and writing configuration files
  2. # Copyright (C) 2011 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for reading and writing configuration files."""
  22. import os
  23. import sys
  24. import tempfile
  25. from io import BytesIO
  26. from unittest import skipIf
  27. from unittest.mock import patch
  28. from dulwich.config import (
  29. CaseInsensitiveOrderedMultiDict,
  30. ConfigDict,
  31. ConfigFile,
  32. StackedConfig,
  33. _check_section_name,
  34. _check_variable_name,
  35. _escape_value,
  36. _format_string,
  37. _parse_string,
  38. apply_instead_of,
  39. parse_submodules,
  40. )
  41. from . import TestCase
  42. class ConfigFileTests(TestCase):
  43. def from_file(self, text):
  44. return ConfigFile.from_file(BytesIO(text))
  45. def test_empty(self) -> None:
  46. ConfigFile()
  47. def test_eq(self) -> None:
  48. self.assertEqual(ConfigFile(), ConfigFile())
  49. def test_default_config(self) -> None:
  50. cf = self.from_file(
  51. b"""[core]
  52. \trepositoryformatversion = 0
  53. \tfilemode = true
  54. \tbare = false
  55. \tlogallrefupdates = true
  56. """
  57. )
  58. self.assertEqual(
  59. ConfigFile(
  60. {
  61. (b"core",): {
  62. b"repositoryformatversion": b"0",
  63. b"filemode": b"true",
  64. b"bare": b"false",
  65. b"logallrefupdates": b"true",
  66. }
  67. }
  68. ),
  69. cf,
  70. )
  71. def test_from_file_empty(self) -> None:
  72. cf = self.from_file(b"")
  73. self.assertEqual(ConfigFile(), cf)
  74. def test_empty_line_before_section(self) -> None:
  75. cf = self.from_file(b"\n[section]\n")
  76. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  77. def test_comment_before_section(self) -> None:
  78. cf = self.from_file(b"# foo\n[section]\n")
  79. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  80. def test_comment_after_section(self) -> None:
  81. cf = self.from_file(b"[section] # foo\n")
  82. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  83. def test_comment_after_variable(self) -> None:
  84. cf = self.from_file(b"[section]\nbar= foo # a comment\n")
  85. self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo"}}), cf)
  86. def test_comment_character_within_value_string(self) -> None:
  87. cf = self.from_file(b'[section]\nbar= "foo#bar"\n')
  88. self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo#bar"}}), cf)
  89. def test_comment_character_within_section_string(self) -> None:
  90. cf = self.from_file(b'[branch "foo#bar"] # a comment\nbar= foo\n')
  91. self.assertEqual(ConfigFile({(b"branch", b"foo#bar"): {b"bar": b"foo"}}), cf)
  92. def test_closing_bracket_within_section_string(self) -> None:
  93. cf = self.from_file(b'[branch "foo]bar"] # a comment\nbar= foo\n')
  94. self.assertEqual(ConfigFile({(b"branch", b"foo]bar"): {b"bar": b"foo"}}), cf)
  95. def test_from_file_section(self) -> None:
  96. cf = self.from_file(b"[core]\nfoo = bar\n")
  97. self.assertEqual(b"bar", cf.get((b"core",), b"foo"))
  98. self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo"))
  99. def test_from_file_multiple(self) -> None:
  100. cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n")
  101. self.assertEqual([b"bar", b"blah"], list(cf.get_multivar((b"core",), b"foo")))
  102. self.assertEqual([], list(cf.get_multivar((b"core",), b"blah")))
  103. def test_from_file_utf8_bom(self) -> None:
  104. text = "[core]\nfoo = b\u00e4r\n".encode("utf-8-sig")
  105. cf = self.from_file(text)
  106. self.assertEqual(b"b\xc3\xa4r", cf.get((b"core",), b"foo"))
  107. def test_from_file_section_case_insensitive_lower(self) -> None:
  108. cf = self.from_file(b"[cOre]\nfOo = bar\n")
  109. self.assertEqual(b"bar", cf.get((b"core",), b"foo"))
  110. self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo"))
  111. def test_from_file_section_case_insensitive_mixed(self) -> None:
  112. cf = self.from_file(b"[cOre]\nfOo = bar\n")
  113. self.assertEqual(b"bar", cf.get((b"core",), b"fOo"))
  114. self.assertEqual(b"bar", cf.get((b"cOre", b"fOo"), b"fOo"))
  115. def test_from_file_with_mixed_quoted(self) -> None:
  116. cf = self.from_file(b'[core]\nfoo = "bar"la\n')
  117. self.assertEqual(b"barla", cf.get((b"core",), b"foo"))
  118. def test_from_file_section_with_open_brackets(self) -> None:
  119. self.assertRaises(ValueError, self.from_file, b"[core\nfoo = bar\n")
  120. def test_from_file_value_with_open_quoted(self) -> None:
  121. self.assertRaises(ValueError, self.from_file, b'[core]\nfoo = "bar\n')
  122. def test_from_file_with_quotes(self) -> None:
  123. cf = self.from_file(b'[core]\nfoo = " bar"\n')
  124. self.assertEqual(b" bar", cf.get((b"core",), b"foo"))
  125. def test_from_file_with_interrupted_line(self) -> None:
  126. cf = self.from_file(b"[core]\nfoo = bar\\\n la\n")
  127. self.assertEqual(b"barla", cf.get((b"core",), b"foo"))
  128. def test_from_file_with_boolean_setting(self) -> None:
  129. cf = self.from_file(b"[core]\nfoo\n")
  130. self.assertEqual(b"true", cf.get((b"core",), b"foo"))
  131. def test_from_file_subsection(self) -> None:
  132. cf = self.from_file(b'[branch "foo"]\nfoo = bar\n')
  133. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  134. def test_from_file_subsection_invalid(self) -> None:
  135. self.assertRaises(ValueError, self.from_file, b'[branch "foo]\nfoo = bar\n')
  136. def test_from_file_subsection_not_quoted(self) -> None:
  137. cf = self.from_file(b"[branch.foo]\nfoo = bar\n")
  138. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  139. def test_from_file_includeif_hasconfig(self) -> None:
  140. """Test parsing includeIf sections with hasconfig conditions."""
  141. # Test case from issue #1216
  142. cf = self.from_file(
  143. b'[includeIf "hasconfig:remote.*.url:ssh://org-*@github.com/**"]\n'
  144. b" path = ~/.config/git/.work\n"
  145. )
  146. self.assertEqual(
  147. b"~/.config/git/.work",
  148. cf.get(
  149. (b"includeIf", b"hasconfig:remote.*.url:ssh://org-*@github.com/**"),
  150. b"path",
  151. ),
  152. )
  153. def test_write_preserve_multivar(self) -> None:
  154. cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n")
  155. f = BytesIO()
  156. cf.write_to_file(f)
  157. self.assertEqual(b"[core]\n\tfoo = bar\n\tfoo = blah\n", f.getvalue())
  158. def test_write_to_file_empty(self) -> None:
  159. c = ConfigFile()
  160. f = BytesIO()
  161. c.write_to_file(f)
  162. self.assertEqual(b"", f.getvalue())
  163. def test_write_to_file_section(self) -> None:
  164. c = ConfigFile()
  165. c.set((b"core",), b"foo", b"bar")
  166. f = BytesIO()
  167. c.write_to_file(f)
  168. self.assertEqual(b"[core]\n\tfoo = bar\n", f.getvalue())
  169. def test_write_to_file_section_multiple(self) -> None:
  170. c = ConfigFile()
  171. c.set((b"core",), b"foo", b"old")
  172. c.set((b"core",), b"foo", b"new")
  173. f = BytesIO()
  174. c.write_to_file(f)
  175. self.assertEqual(b"[core]\n\tfoo = new\n", f.getvalue())
  176. def test_write_to_file_subsection(self) -> None:
  177. c = ConfigFile()
  178. c.set((b"branch", b"blie"), b"foo", b"bar")
  179. f = BytesIO()
  180. c.write_to_file(f)
  181. self.assertEqual(b'[branch "blie"]\n\tfoo = bar\n', f.getvalue())
  182. def test_same_line(self) -> None:
  183. cf = self.from_file(b"[branch.foo] foo = bar\n")
  184. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  185. def test_quoted_newlines_windows(self) -> None:
  186. cf = self.from_file(
  187. b"[alias]\r\n"
  188. b"c = '!f() { \\\r\n"
  189. b' printf \'[git commit -m \\"%s\\"]\\n\' \\"$*\\" && \\\r\n'
  190. b' git commit -m \\"$*\\"; \\\r\n'
  191. b" }; f'\r\n"
  192. )
  193. self.assertEqual(list(cf.sections()), [(b"alias",)])
  194. self.assertEqual(
  195. b'\'!f() { printf \'[git commit -m "%s"]\n\' "$*" && git commit -m "$*"',
  196. cf.get((b"alias",), b"c"),
  197. )
  198. def test_quoted(self) -> None:
  199. cf = self.from_file(
  200. b"""[gui]
  201. \tfontdiff = -family \\\"Ubuntu Mono\\\" -size 11 -overstrike 0
  202. """
  203. )
  204. self.assertEqual(
  205. ConfigFile(
  206. {
  207. (b"gui",): {
  208. b"fontdiff": b'-family "Ubuntu Mono" -size 11 -overstrike 0',
  209. }
  210. }
  211. ),
  212. cf,
  213. )
  214. def test_quoted_multiline(self) -> None:
  215. cf = self.from_file(
  216. b"""[alias]
  217. who = \"!who() {\\
  218. git log --no-merges --pretty=format:'%an - %ae' $@ | uniq -c | sort -rn;\\
  219. };\\
  220. who\"
  221. """
  222. )
  223. self.assertEqual(
  224. ConfigFile(
  225. {
  226. (b"alias",): {
  227. b"who": (
  228. b"!who() {git log --no-merges --pretty=format:'%an - "
  229. b"%ae' $@ | uniq -c | sort -rn;};who"
  230. )
  231. }
  232. }
  233. ),
  234. cf,
  235. )
  236. def test_set_hash_gets_quoted(self) -> None:
  237. c = ConfigFile()
  238. c.set(b"xandikos", b"color", b"#665544")
  239. f = BytesIO()
  240. c.write_to_file(f)
  241. self.assertEqual(b'[xandikos]\n\tcolor = "#665544"\n', f.getvalue())
  242. def test_windows_path_with_trailing_backslash_unquoted(self) -> None:
  243. """Test that Windows paths ending with escaped backslash are handled correctly."""
  244. # This reproduces the issue from https://github.com/jelmer/dulwich/issues/1088
  245. # A single backslash at the end should actually be a line continuation in strict Git config
  246. # But we want to be more tolerant like Git itself
  247. cf = self.from_file(
  248. b'[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n\turl = C:/Users/test\\\\\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
  249. )
  250. self.assertEqual(b"C:/Users/test\\", cf.get((b"remote", b"origin"), b"url"))
  251. self.assertEqual(
  252. b"+refs/heads/*:refs/remotes/origin/*",
  253. cf.get((b"remote", b"origin"), b"fetch"),
  254. )
  255. def test_windows_path_with_trailing_backslash_quoted(self) -> None:
  256. """Test that quoted Windows paths with escaped backslashes work correctly."""
  257. cf = self.from_file(
  258. b'[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n\turl = "C:\\\\Users\\\\test\\\\"\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
  259. )
  260. self.assertEqual(b"C:\\Users\\test\\", cf.get((b"remote", b"origin"), b"url"))
  261. self.assertEqual(
  262. b"+refs/heads/*:refs/remotes/origin/*",
  263. cf.get((b"remote", b"origin"), b"fetch"),
  264. )
  265. def test_single_backslash_at_line_end_shows_proper_escaping_needed(self) -> None:
  266. """Test that demonstrates proper escaping is needed for single backslashes."""
  267. # This test documents the current behavior: a single backslash at the end of a line
  268. # is treated as a line continuation per Git config spec. Users should escape backslashes.
  269. # This reproduces the original issue - single backslash causes line continuation
  270. cf = self.from_file(
  271. b'[remote "origin"]\n\turl = C:/Users/test\\\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
  272. )
  273. # The result shows that line continuation occurred
  274. self.assertEqual(
  275. b"C:/Users/testfetch = +refs/heads/*:refs/remotes/origin/*",
  276. cf.get((b"remote", b"origin"), b"url"),
  277. )
  278. # The proper way to include a literal backslash is to escape it
  279. cf2 = self.from_file(
  280. b'[remote "origin"]\n\turl = C:/Users/test\\\\\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
  281. )
  282. self.assertEqual(b"C:/Users/test\\", cf2.get((b"remote", b"origin"), b"url"))
  283. self.assertEqual(
  284. b"+refs/heads/*:refs/remotes/origin/*",
  285. cf2.get((b"remote", b"origin"), b"fetch"),
  286. )
  287. def test_from_path_pathlib(self) -> None:
  288. import tempfile
  289. from pathlib import Path
  290. # Create a temporary config file
  291. with tempfile.NamedTemporaryFile(mode="w", suffix=".config", delete=False) as f:
  292. f.write("[core]\n filemode = true\n")
  293. temp_path = f.name
  294. self.addCleanup(os.unlink, temp_path)
  295. # Test with pathlib.Path
  296. path_obj = Path(temp_path)
  297. cf = ConfigFile.from_path(path_obj)
  298. self.assertEqual(cf.get((b"core",), b"filemode"), b"true")
  299. def test_write_to_path_pathlib(self) -> None:
  300. import tempfile
  301. from pathlib import Path
  302. # Create a config
  303. cf = ConfigFile()
  304. cf.set((b"user",), b"name", b"Test User")
  305. # Write to pathlib.Path
  306. with tempfile.NamedTemporaryFile(suffix=".config", delete=False) as f:
  307. temp_path = f.name
  308. try:
  309. path_obj = Path(temp_path)
  310. cf.write_to_path(path_obj)
  311. # Read it back
  312. cf2 = ConfigFile.from_path(path_obj)
  313. self.assertEqual(cf2.get((b"user",), b"name"), b"Test User")
  314. finally:
  315. # Clean up
  316. os.unlink(temp_path)
  317. def test_include_basic(self) -> None:
  318. """Test basic include functionality."""
  319. with tempfile.TemporaryDirectory() as tmpdir:
  320. # Create included config file
  321. included_path = os.path.join(tmpdir, "included.config")
  322. with open(included_path, "wb") as f:
  323. f.write(
  324. b"[user]\n name = Included User\n email = included@example.com\n"
  325. )
  326. # Create main config with include
  327. main_config = self.from_file(
  328. b"[user]\n name = Main User\n[include]\n path = included.config\n"
  329. )
  330. # Should not include anything without proper directory context
  331. self.assertEqual(b"Main User", main_config.get((b"user",), b"name"))
  332. with self.assertRaises(KeyError):
  333. main_config.get((b"user",), b"email")
  334. # Now test with proper file loading
  335. main_path = os.path.join(tmpdir, "main.config")
  336. with open(main_path, "wb") as f:
  337. f.write(
  338. b"[user]\n name = Main User\n[include]\n path = included.config\n"
  339. )
  340. # Load from path to get include functionality
  341. cf = ConfigFile.from_path(main_path)
  342. self.assertEqual(b"Included User", cf.get((b"user",), b"name"))
  343. self.assertEqual(b"included@example.com", cf.get((b"user",), b"email"))
  344. def test_include_absolute_path(self) -> None:
  345. """Test include with absolute path."""
  346. with tempfile.TemporaryDirectory() as tmpdir:
  347. # Use realpath to resolve any symlinks (important on macOS and Windows)
  348. tmpdir = os.path.realpath(tmpdir)
  349. # Create included config file
  350. included_path = os.path.join(tmpdir, "included.config")
  351. with open(included_path, "wb") as f:
  352. f.write(b"[core]\n bare = true\n")
  353. # Create main config with absolute include path
  354. main_path = os.path.join(tmpdir, "main.config")
  355. with open(main_path, "wb") as f:
  356. # Properly escape backslashes in Windows paths
  357. escaped_path = included_path.replace("\\", "\\\\")
  358. f.write(f"[include]\n path = {escaped_path}\n".encode())
  359. cf = ConfigFile.from_path(main_path)
  360. self.assertEqual(b"true", cf.get((b"core",), b"bare"))
  361. def test_includeif_hasconfig(self) -> None:
  362. """Test includeIf with hasconfig conditions."""
  363. with tempfile.TemporaryDirectory() as tmpdir:
  364. # Create included config file
  365. work_included_path = os.path.join(tmpdir, "work.config")
  366. with open(work_included_path, "wb") as f:
  367. f.write(b"[user]\n email = work@company.com\n")
  368. personal_included_path = os.path.join(tmpdir, "personal.config")
  369. with open(personal_included_path, "wb") as f:
  370. f.write(b"[user]\n email = personal@example.com\n")
  371. # Create main config with hasconfig conditions
  372. main_path = os.path.join(tmpdir, "main.config")
  373. with open(main_path, "wb") as f:
  374. f.write(
  375. b'[remote "origin"]\n'
  376. b" url = ssh://org-work@github.com/company/project\n"
  377. b'[includeIf "hasconfig:remote.*.url:ssh://org-*@github.com/**"]\n'
  378. b" path = work.config\n"
  379. b'[includeIf "hasconfig:remote.*.url:https://github.com/opensource/**"]\n'
  380. b" path = personal.config\n"
  381. )
  382. # Load config - should match the work config due to org-work remote
  383. # The second condition won't match since url doesn't have /opensource/ path
  384. cf = ConfigFile.from_path(main_path)
  385. self.assertEqual(b"work@company.com", cf.get((b"user",), b"email"))
  386. def test_includeif_hasconfig_wildcard(self) -> None:
  387. """Test includeIf hasconfig with wildcard patterns."""
  388. with tempfile.TemporaryDirectory() as tmpdir:
  389. # Create included config
  390. included_path = os.path.join(tmpdir, "included.config")
  391. with open(included_path, "wb") as f:
  392. f.write(b"[user]\n name = IncludedUser\n")
  393. # Create main config with hasconfig condition using wildcards
  394. main_path = os.path.join(tmpdir, "main.config")
  395. with open(main_path, "wb") as f:
  396. f.write(
  397. b"[core]\n"
  398. b" autocrlf = true\n"
  399. b'[includeIf "hasconfig:core.autocrlf:true"]\n'
  400. b" path = included.config\n"
  401. )
  402. # Load config - should include based on core.autocrlf value
  403. cf = ConfigFile.from_path(main_path)
  404. self.assertEqual(b"IncludedUser", cf.get((b"user",), b"name"))
  405. def test_includeif_hasconfig_no_match(self) -> None:
  406. """Test includeIf hasconfig when condition doesn't match."""
  407. with tempfile.TemporaryDirectory() as tmpdir:
  408. # Create included config
  409. included_path = os.path.join(tmpdir, "included.config")
  410. with open(included_path, "wb") as f:
  411. f.write(b"[user]\n name = IncludedUser\n")
  412. # Create main config with non-matching hasconfig condition
  413. main_path = os.path.join(tmpdir, "main.config")
  414. with open(main_path, "wb") as f:
  415. f.write(
  416. b"[core]\n"
  417. b" autocrlf = false\n"
  418. b'[includeIf "hasconfig:core.autocrlf:true"]\n'
  419. b" path = included.config\n"
  420. )
  421. # Load config - should NOT include since condition doesn't match
  422. cf = ConfigFile.from_path(main_path)
  423. with self.assertRaises(KeyError):
  424. cf.get((b"user",), b"name")
  425. def test_include_circular(self) -> None:
  426. """Test that circular includes are handled properly."""
  427. with tempfile.TemporaryDirectory() as tmpdir:
  428. # Create two configs that include each other
  429. config1_path = os.path.join(tmpdir, "config1")
  430. config2_path = os.path.join(tmpdir, "config2")
  431. with open(config1_path, "wb") as f:
  432. f.write(b"[user]\n name = User1\n[include]\n path = config2\n")
  433. with open(config2_path, "wb") as f:
  434. f.write(
  435. b"[user]\n email = user2@example.com\n[include]\n path = config1\n"
  436. )
  437. # Should handle circular includes gracefully
  438. cf = ConfigFile.from_path(config1_path)
  439. self.assertEqual(b"User1", cf.get((b"user",), b"name"))
  440. self.assertEqual(b"user2@example.com", cf.get((b"user",), b"email"))
  441. def test_include_missing_file(self) -> None:
  442. """Test that missing include files are ignored."""
  443. with tempfile.TemporaryDirectory() as tmpdir:
  444. # Create config with include of non-existent file
  445. config_path = os.path.join(tmpdir, "config")
  446. with open(config_path, "wb") as f:
  447. f.write(
  448. b"[user]\n name = TestUser\n[include]\n path = missing.config\n"
  449. )
  450. # Should not fail, just ignore missing include
  451. cf = ConfigFile.from_path(config_path)
  452. self.assertEqual(b"TestUser", cf.get((b"user",), b"name"))
  453. def test_include_depth_limit(self) -> None:
  454. """Test that excessive include depth is prevented."""
  455. with tempfile.TemporaryDirectory() as tmpdir:
  456. # Create a chain of includes that exceeds depth limit
  457. for i in range(15):
  458. config_path = os.path.join(tmpdir, f"config{i}")
  459. with open(config_path, "wb") as f:
  460. if i == 0:
  461. f.write(b"[user]\n name = User0\n")
  462. f.write(f"[include]\n path = config{i + 1}\n".encode())
  463. # Should raise error due to depth limit
  464. with self.assertRaises(ValueError) as cm:
  465. ConfigFile.from_path(os.path.join(tmpdir, "config0"))
  466. self.assertIn("include depth", str(cm.exception))
  467. def test_include_with_custom_file_opener(self) -> None:
  468. """Test include functionality with a custom file opener for security."""
  469. with tempfile.TemporaryDirectory() as tmpdir:
  470. # Create config files
  471. included_path = os.path.join(tmpdir, "included.config")
  472. with open(included_path, "wb") as f:
  473. f.write(b"[user]\n email = custom@example.com\n")
  474. restricted_path = os.path.join(tmpdir, "restricted.config")
  475. with open(restricted_path, "wb") as f:
  476. f.write(b"[user]\n email = restricted@example.com\n")
  477. main_path = os.path.join(tmpdir, "main.config")
  478. with open(main_path, "wb") as f:
  479. f.write(b"[user]\n name = Test User\n")
  480. f.write(b"[include]\n path = included.config\n")
  481. f.write(b"[include]\n path = restricted.config\n")
  482. # Define a custom file opener that restricts access
  483. allowed_files = {included_path, main_path}
  484. def secure_file_opener(path):
  485. path_str = os.fspath(path)
  486. if path_str not in allowed_files:
  487. raise PermissionError(f"Access denied to {path}")
  488. return open(path_str, "rb")
  489. # Load config with restricted file access
  490. cf = ConfigFile.from_path(main_path, file_opener=secure_file_opener)
  491. # Should have the main config and included config, but not restricted
  492. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  493. self.assertEqual(b"custom@example.com", cf.get((b"user",), b"email"))
  494. # Email from restricted.config should not be loaded
  495. def test_unknown_includeif_condition(self) -> None:
  496. """Test that unknown includeIf conditions are silently ignored (like Git)."""
  497. with tempfile.TemporaryDirectory() as tmpdir:
  498. # Create included config file
  499. included_path = os.path.join(tmpdir, "included.config")
  500. with open(included_path, "wb") as f:
  501. f.write(b"[user]\n email = included@example.com\n")
  502. # Create main config with unknown includeIf condition
  503. main_path = os.path.join(tmpdir, "main.config")
  504. with open(main_path, "wb") as f:
  505. f.write(b"[user]\n name = Main User\n")
  506. f.write(
  507. b'[includeIf "unknowncondition:foo"]\n path = included.config\n'
  508. )
  509. # Should not fail, just ignore the unknown condition
  510. cf = ConfigFile.from_path(main_path)
  511. self.assertEqual(b"Main User", cf.get((b"user",), b"name"))
  512. # Email should not be included because condition is unknown
  513. with self.assertRaises(KeyError):
  514. cf.get((b"user",), b"email")
  515. def test_missing_include_file_logging(self) -> None:
  516. """Test that missing include files are logged but don't cause failure."""
  517. import logging
  518. from io import StringIO
  519. # Set up logging capture
  520. log_capture = StringIO()
  521. handler = logging.StreamHandler(log_capture)
  522. handler.setLevel(logging.DEBUG)
  523. logger = logging.getLogger("dulwich.config")
  524. logger.addHandler(handler)
  525. logger.setLevel(logging.DEBUG)
  526. try:
  527. with tempfile.TemporaryDirectory() as tmpdir:
  528. config_path = os.path.join(tmpdir, "test.config")
  529. with open(config_path, "wb") as f:
  530. f.write(b"[user]\n name = Test User\n")
  531. f.write(b"[include]\n path = nonexistent.config\n")
  532. # Should not fail, just log
  533. cf = ConfigFile.from_path(config_path)
  534. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  535. # Check that it was logged
  536. log_output = log_capture.getvalue()
  537. self.assertIn("Invalid include path", log_output)
  538. self.assertIn("nonexistent.config", log_output)
  539. finally:
  540. logger.removeHandler(handler)
  541. def test_invalid_include_path_logging(self) -> None:
  542. """Test that invalid include paths are logged but don't cause failure."""
  543. import logging
  544. from io import StringIO
  545. # Set up logging capture
  546. log_capture = StringIO()
  547. handler = logging.StreamHandler(log_capture)
  548. handler.setLevel(logging.DEBUG)
  549. logger = logging.getLogger("dulwich.config")
  550. logger.addHandler(handler)
  551. logger.setLevel(logging.DEBUG)
  552. try:
  553. with tempfile.TemporaryDirectory() as tmpdir:
  554. config_path = os.path.join(tmpdir, "test.config")
  555. with open(config_path, "wb") as f:
  556. f.write(b"[user]\n name = Test User\n")
  557. # Use null bytes which are invalid in paths
  558. f.write(b"[include]\n path = /invalid\x00path/file.config\n")
  559. # Should not fail, just log
  560. cf = ConfigFile.from_path(config_path)
  561. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  562. # Check that it was logged
  563. log_output = log_capture.getvalue()
  564. self.assertIn("Invalid include path", log_output)
  565. finally:
  566. logger.removeHandler(handler)
  567. def test_unknown_includeif_condition_logging(self) -> None:
  568. """Test that unknown includeIf conditions are logged."""
  569. import logging
  570. from io import StringIO
  571. # Set up logging capture
  572. log_capture = StringIO()
  573. handler = logging.StreamHandler(log_capture)
  574. handler.setLevel(logging.DEBUG)
  575. logger = logging.getLogger("dulwich.config")
  576. logger.addHandler(handler)
  577. logger.setLevel(logging.DEBUG)
  578. try:
  579. with tempfile.TemporaryDirectory() as tmpdir:
  580. config_path = os.path.join(tmpdir, "test.config")
  581. with open(config_path, "wb") as f:
  582. f.write(b"[user]\n name = Test User\n")
  583. f.write(
  584. b'[includeIf "futurefeature:value"]\n path = other.config\n'
  585. )
  586. # Should not fail, just log
  587. cf = ConfigFile.from_path(config_path)
  588. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  589. # Check that it was logged
  590. log_output = log_capture.getvalue()
  591. self.assertIn("Unknown includeIf condition", log_output)
  592. self.assertIn("futurefeature:value", log_output)
  593. finally:
  594. logger.removeHandler(handler)
  595. def test_custom_file_opener_with_include_depth(self) -> None:
  596. """Test that custom file opener is passed through include chain."""
  597. with tempfile.TemporaryDirectory() as tmpdir:
  598. # Use realpath to resolve any symlinks
  599. tmpdir = os.path.realpath(tmpdir)
  600. # Create a chain of includes
  601. final_config = os.path.join(tmpdir, "final.config")
  602. with open(final_config, "wb") as f:
  603. f.write(b"[feature]\n enabled = true\n")
  604. middle_config = os.path.join(tmpdir, "middle.config")
  605. with open(middle_config, "wb") as f:
  606. f.write(b"[user]\n email = test@example.com\n")
  607. escaped_final_config = final_config.replace("\\", "\\\\")
  608. f.write(f"[include]\n path = {escaped_final_config}\n".encode())
  609. main_config = os.path.join(tmpdir, "main.config")
  610. with open(main_config, "wb") as f:
  611. f.write(b"[user]\n name = Test User\n")
  612. escaped_middle_config = middle_config.replace("\\", "\\\\")
  613. f.write(f"[include]\n path = {escaped_middle_config}\n".encode())
  614. # Track file access order
  615. access_order = []
  616. def ordering_file_opener(path):
  617. path_str = os.fspath(path)
  618. access_order.append(os.path.basename(path_str))
  619. return open(path_str, "rb")
  620. # Load config
  621. cf = ConfigFile.from_path(main_config, file_opener=ordering_file_opener)
  622. # Verify all values were loaded
  623. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  624. self.assertEqual(b"test@example.com", cf.get((b"user",), b"email"))
  625. self.assertEqual(b"true", cf.get((b"feature",), b"enabled"))
  626. # Verify access order
  627. self.assertEqual(
  628. ["main.config", "middle.config", "final.config"], access_order
  629. )
  630. class ConfigDictTests(TestCase):
  631. def test_get_set(self) -> None:
  632. cd = ConfigDict()
  633. self.assertRaises(KeyError, cd.get, b"foo", b"core")
  634. cd.set((b"core",), b"foo", b"bla")
  635. self.assertEqual(b"bla", cd.get((b"core",), b"foo"))
  636. cd.set((b"core",), b"foo", b"bloe")
  637. self.assertEqual(b"bloe", cd.get((b"core",), b"foo"))
  638. def test_get_boolean(self) -> None:
  639. cd = ConfigDict()
  640. cd.set((b"core",), b"foo", b"true")
  641. self.assertTrue(cd.get_boolean((b"core",), b"foo"))
  642. cd.set((b"core",), b"foo", b"false")
  643. self.assertFalse(cd.get_boolean((b"core",), b"foo"))
  644. cd.set((b"core",), b"foo", b"invalid")
  645. self.assertRaises(ValueError, cd.get_boolean, (b"core",), b"foo")
  646. def test_dict(self) -> None:
  647. cd = ConfigDict()
  648. cd.set((b"core",), b"foo", b"bla")
  649. cd.set((b"core2",), b"foo", b"bloe")
  650. self.assertEqual([(b"core",), (b"core2",)], list(cd.keys()))
  651. self.assertEqual(cd[(b"core",)], {b"foo": b"bla"})
  652. cd[b"a"] = b"b"
  653. self.assertEqual(cd[b"a"], b"b")
  654. def test_items(self) -> None:
  655. cd = ConfigDict()
  656. cd.set((b"core",), b"foo", b"bla")
  657. cd.set((b"core2",), b"foo", b"bloe")
  658. self.assertEqual([(b"foo", b"bla")], list(cd.items((b"core",))))
  659. def test_items_nonexistant(self) -> None:
  660. cd = ConfigDict()
  661. cd.set((b"core2",), b"foo", b"bloe")
  662. self.assertEqual([], list(cd.items((b"core",))))
  663. def test_sections(self) -> None:
  664. cd = ConfigDict()
  665. cd.set((b"core2",), b"foo", b"bloe")
  666. self.assertEqual([(b"core2",)], list(cd.sections()))
  667. def test_set_vs_add(self) -> None:
  668. cd = ConfigDict()
  669. # Test add() creates multivars
  670. cd.add((b"core",), b"foo", b"value1")
  671. cd.add((b"core",), b"foo", b"value2")
  672. self.assertEqual(
  673. [b"value1", b"value2"], list(cd.get_multivar((b"core",), b"foo"))
  674. )
  675. # Test set() replaces values
  676. cd.set((b"core",), b"foo", b"value3")
  677. self.assertEqual([b"value3"], list(cd.get_multivar((b"core",), b"foo")))
  678. self.assertEqual(b"value3", cd.get((b"core",), b"foo"))
  679. class StackedConfigTests(TestCase):
  680. def test_default_backends(self) -> None:
  681. StackedConfig.default_backends()
  682. @skipIf(sys.platform != "win32", "Windows specific config location.")
  683. def test_windows_config_from_path(self) -> None:
  684. from dulwich.config import get_win_system_paths
  685. install_dir = os.path.join("C:", "foo", "Git")
  686. self.overrideEnv("PATH", os.path.join(install_dir, "cmd"))
  687. with patch("os.path.exists", return_value=True):
  688. paths = set(get_win_system_paths())
  689. self.assertEqual(
  690. {
  691. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  692. os.path.join(install_dir, "etc", "gitconfig"),
  693. },
  694. paths,
  695. )
  696. @skipIf(sys.platform != "win32", "Windows specific config location.")
  697. def test_windows_config_from_reg(self) -> None:
  698. import winreg
  699. from dulwich.config import get_win_system_paths
  700. self.overrideEnv("PATH", None)
  701. install_dir = os.path.join("C:", "foo", "Git")
  702. with patch("winreg.OpenKey"):
  703. with patch(
  704. "winreg.QueryValueEx",
  705. return_value=(install_dir, winreg.REG_SZ),
  706. ):
  707. paths = set(get_win_system_paths())
  708. self.assertEqual(
  709. {
  710. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  711. os.path.join(install_dir, "etc", "gitconfig"),
  712. },
  713. paths,
  714. )
  715. class EscapeValueTests(TestCase):
  716. def test_nothing(self) -> None:
  717. self.assertEqual(b"foo", _escape_value(b"foo"))
  718. def test_backslash(self) -> None:
  719. self.assertEqual(b"foo\\\\", _escape_value(b"foo\\"))
  720. def test_newline(self) -> None:
  721. self.assertEqual(b"foo\\n", _escape_value(b"foo\n"))
  722. class FormatStringTests(TestCase):
  723. def test_quoted(self) -> None:
  724. self.assertEqual(b'" foo"', _format_string(b" foo"))
  725. self.assertEqual(b'"\\tfoo"', _format_string(b"\tfoo"))
  726. def test_not_quoted(self) -> None:
  727. self.assertEqual(b"foo", _format_string(b"foo"))
  728. self.assertEqual(b"foo bar", _format_string(b"foo bar"))
  729. class ParseStringTests(TestCase):
  730. def test_quoted(self) -> None:
  731. self.assertEqual(b" foo", _parse_string(b'" foo"'))
  732. self.assertEqual(b"\tfoo", _parse_string(b'"\\tfoo"'))
  733. def test_not_quoted(self) -> None:
  734. self.assertEqual(b"foo", _parse_string(b"foo"))
  735. self.assertEqual(b"foo bar", _parse_string(b"foo bar"))
  736. def test_nothing(self) -> None:
  737. self.assertEqual(b"", _parse_string(b""))
  738. def test_tab(self) -> None:
  739. self.assertEqual(b"\tbar\t", _parse_string(b"\\tbar\\t"))
  740. def test_newline(self) -> None:
  741. self.assertEqual(b"\nbar\t", _parse_string(b"\\nbar\\t\t"))
  742. def test_quote(self) -> None:
  743. self.assertEqual(b'"foo"', _parse_string(b'\\"foo\\"'))
  744. class CheckVariableNameTests(TestCase):
  745. def test_invalid(self) -> None:
  746. self.assertFalse(_check_variable_name(b"foo "))
  747. self.assertFalse(_check_variable_name(b"bar,bar"))
  748. self.assertFalse(_check_variable_name(b"bar.bar"))
  749. def test_valid(self) -> None:
  750. self.assertTrue(_check_variable_name(b"FOO"))
  751. self.assertTrue(_check_variable_name(b"foo"))
  752. self.assertTrue(_check_variable_name(b"foo-bar"))
  753. class CheckSectionNameTests(TestCase):
  754. def test_invalid(self) -> None:
  755. self.assertFalse(_check_section_name(b"foo "))
  756. self.assertFalse(_check_section_name(b"bar,bar"))
  757. def test_valid(self) -> None:
  758. self.assertTrue(_check_section_name(b"FOO"))
  759. self.assertTrue(_check_section_name(b"foo"))
  760. self.assertTrue(_check_section_name(b"foo-bar"))
  761. self.assertTrue(_check_section_name(b"bar.bar"))
  762. class SubmodulesTests(TestCase):
  763. def testSubmodules(self) -> None:
  764. cf = ConfigFile.from_file(
  765. BytesIO(
  766. b"""\
  767. [submodule "core/lib"]
  768. \tpath = core/lib
  769. \turl = https://github.com/phhusson/QuasselC.git
  770. """
  771. )
  772. )
  773. got = list(parse_submodules(cf))
  774. self.assertEqual(
  775. [
  776. (
  777. b"core/lib",
  778. b"https://github.com/phhusson/QuasselC.git",
  779. b"core/lib",
  780. )
  781. ],
  782. got,
  783. )
  784. def testMalformedSubmodules(self) -> None:
  785. cf = ConfigFile.from_file(
  786. BytesIO(
  787. b"""\
  788. [submodule "core/lib"]
  789. \tpath = core/lib
  790. \turl = https://github.com/phhusson/QuasselC.git
  791. [submodule "dulwich"]
  792. \turl = https://github.com/jelmer/dulwich
  793. """
  794. )
  795. )
  796. got = list(parse_submodules(cf))
  797. self.assertEqual(
  798. [
  799. (
  800. b"core/lib",
  801. b"https://github.com/phhusson/QuasselC.git",
  802. b"core/lib",
  803. )
  804. ],
  805. got,
  806. )
  807. class ApplyInsteadOfTests(TestCase):
  808. def test_none(self) -> None:
  809. config = ConfigDict()
  810. self.assertEqual(
  811. "https://example.com/", apply_instead_of(config, "https://example.com/")
  812. )
  813. def test_apply(self) -> None:
  814. config = ConfigDict()
  815. config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  816. self.assertEqual(
  817. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  818. )
  819. def test_apply_multiple(self) -> None:
  820. config = ConfigDict()
  821. config.add(("url", "https://samba.org/"), "insteadOf", "https://blah.com/")
  822. config.add(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  823. self.assertEqual(
  824. [b"https://blah.com/", b"https://example.com/"],
  825. list(config.get_multivar(("url", "https://samba.org/"), "insteadOf")),
  826. )
  827. self.assertEqual(
  828. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  829. )
  830. def test_apply_preserves_case_in_subsection(self) -> None:
  831. """Test that mixed-case URLs (like those with access tokens) are preserved."""
  832. config = ConfigDict()
  833. # GitHub access tokens have mixed case that must be preserved
  834. url_with_token = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/"
  835. config.set(("url", url_with_token), "insteadOf", "https://github.com/")
  836. # Apply the substitution
  837. result = apply_instead_of(config, "https://github.com/jelmer/dulwich.git")
  838. expected = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/jelmer/dulwich.git"
  839. self.assertEqual(expected, result)
  840. # Verify the token case is preserved
  841. self.assertIn("ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890", result)
  842. class CaseInsensitiveConfigTests(TestCase):
  843. def test_case_insensitive(self) -> None:
  844. config = CaseInsensitiveOrderedMultiDict()
  845. config[("core",)] = "value"
  846. self.assertEqual("value", config[("CORE",)])
  847. self.assertEqual("value", config[("CoRe",)])
  848. self.assertEqual([("core",)], list(config.keys()))
  849. def test_multiple_set(self) -> None:
  850. config = CaseInsensitiveOrderedMultiDict()
  851. config[("core",)] = "value1"
  852. config[("core",)] = "value2"
  853. # The second set overwrites the first one
  854. self.assertEqual("value2", config[("core",)])
  855. self.assertEqual("value2", config[("CORE",)])
  856. def test_get_all(self) -> None:
  857. config = CaseInsensitiveOrderedMultiDict()
  858. config[("core",)] = "value1"
  859. config[("CORE",)] = "value2"
  860. config[("CoRe",)] = "value3"
  861. self.assertEqual(
  862. ["value1", "value2", "value3"], list(config.get_all(("core",)))
  863. )
  864. self.assertEqual(
  865. ["value1", "value2", "value3"], list(config.get_all(("CORE",)))
  866. )
  867. def test_delitem(self) -> None:
  868. config = CaseInsensitiveOrderedMultiDict()
  869. config[("core",)] = "value1"
  870. config[("CORE",)] = "value2"
  871. config[("other",)] = "value3"
  872. del config[("core",)]
  873. self.assertNotIn(("core",), config)
  874. self.assertNotIn(("CORE",), config)
  875. self.assertEqual("value3", config[("other",)])
  876. self.assertEqual(1, len(config))
  877. def test_len(self) -> None:
  878. config = CaseInsensitiveOrderedMultiDict()
  879. self.assertEqual(0, len(config))
  880. config[("core",)] = "value1"
  881. self.assertEqual(1, len(config))
  882. config[("CORE",)] = "value2"
  883. self.assertEqual(1, len(config)) # Same key, case insensitive
  884. def test_subsection_case_preserved(self) -> None:
  885. """Test that subsection names preserve their case."""
  886. config = CaseInsensitiveOrderedMultiDict()
  887. # Section names should be case-insensitive, but subsection names should preserve case
  888. config[("url", "https://Example.COM/Path")] = "value1"
  889. # Can retrieve with different case section name
  890. self.assertEqual("value1", config[("URL", "https://Example.COM/Path")])
  891. self.assertEqual("value1", config[("url", "https://Example.COM/Path")])
  892. # But not with different case subsection name
  893. with self.assertRaises(KeyError):
  894. config[("url", "https://example.com/path")]
  895. # Verify the stored key preserves subsection case
  896. stored_keys = list(config.keys())
  897. self.assertEqual(1, len(stored_keys))
  898. self.assertEqual(("url", "https://Example.COM/Path"), stored_keys[0])
  899. config[("other",)] = "value3"
  900. self.assertEqual(2, len(config))
  901. def test_make_from_dict(self) -> None:
  902. original = {("core",): "value1", ("other",): "value2"}
  903. config = CaseInsensitiveOrderedMultiDict.make(original)
  904. self.assertEqual("value1", config[("core",)])
  905. self.assertEqual("value1", config[("CORE",)])
  906. self.assertEqual("value2", config[("other",)])
  907. def test_make_from_self(self) -> None:
  908. config1 = CaseInsensitiveOrderedMultiDict()
  909. config1[("core",)] = "value"
  910. config2 = CaseInsensitiveOrderedMultiDict.make(config1)
  911. self.assertIs(config1, config2)
  912. def test_make_invalid_type(self) -> None:
  913. self.assertRaises(TypeError, CaseInsensitiveOrderedMultiDict.make, "invalid")
  914. def test_get_with_default(self) -> None:
  915. config = CaseInsensitiveOrderedMultiDict()
  916. config[("core",)] = "value"
  917. self.assertEqual("value", config.get(("core",)))
  918. self.assertEqual("value", config.get(("CORE",)))
  919. self.assertEqual("default", config.get(("missing",), "default"))
  920. # Test default_factory behavior
  921. config_with_factory = CaseInsensitiveOrderedMultiDict(
  922. default_factory=CaseInsensitiveOrderedMultiDict
  923. )
  924. result = config_with_factory.get(("missing",))
  925. self.assertIsInstance(result, CaseInsensitiveOrderedMultiDict)
  926. self.assertEqual(0, len(result))
  927. def test_setdefault(self) -> None:
  928. config = CaseInsensitiveOrderedMultiDict()
  929. # Set new value
  930. result1 = config.setdefault(("core",), "value1")
  931. self.assertEqual("value1", result1)
  932. self.assertEqual("value1", config[("core",)])
  933. # Try to set again with different case - should return existing
  934. result2 = config.setdefault(("CORE",), "value2")
  935. self.assertEqual("value1", result2)
  936. self.assertEqual("value1", config[("core",)])
  937. def test_values(self) -> None:
  938. config = CaseInsensitiveOrderedMultiDict()
  939. config[("core",)] = "value1"
  940. config[("other",)] = "value2"
  941. config[("CORE",)] = "value3" # Overwrites previous core value
  942. self.assertEqual({"value3", "value2"}, set(config.values()))
  943. def test_items_iteration(self) -> None:
  944. config = CaseInsensitiveOrderedMultiDict()
  945. config[("core",)] = "value1"
  946. config[("other",)] = "value2"
  947. config[("CORE",)] = "value3"
  948. items = list(config.items())
  949. self.assertEqual(3, len(items))
  950. self.assertEqual((("core",), "value1"), items[0])
  951. self.assertEqual((("other",), "value2"), items[1])
  952. self.assertEqual((("CORE",), "value3"), items[2])
  953. def test_str_keys(self) -> None:
  954. config = CaseInsensitiveOrderedMultiDict()
  955. config["core"] = "value"
  956. self.assertEqual("value", config["CORE"])
  957. self.assertEqual("value", config["CoRe"])
  958. def test_nested_tuple_keys(self) -> None:
  959. config = CaseInsensitiveOrderedMultiDict()
  960. config[("branch", "master")] = "value"
  961. # Section names are case-insensitive
  962. self.assertEqual("value", config[("BRANCH", "master")])
  963. self.assertEqual("value", config[("Branch", "master")])
  964. # But subsection names are case-sensitive
  965. with self.assertRaises(KeyError):
  966. config[("branch", "MASTER")]
  967. class ConfigFileSetTests(TestCase):
  968. def test_set_replaces_value(self) -> None:
  969. # Test that set() replaces the value instead of appending
  970. cf = ConfigFile()
  971. cf.set((b"core",), b"sshCommand", b"ssh -i ~/.ssh/id_rsa1")
  972. cf.set((b"core",), b"sshCommand", b"ssh -i ~/.ssh/id_rsa2")
  973. # Should only have one value
  974. self.assertEqual(b"ssh -i ~/.ssh/id_rsa2", cf.get((b"core",), b"sshCommand"))
  975. # When written to file, should only have one entry
  976. f = BytesIO()
  977. cf.write_to_file(f)
  978. content = f.getvalue()
  979. self.assertEqual(1, content.count(b"sshCommand"))
  980. self.assertIn(b"sshCommand = ssh -i ~/.ssh/id_rsa2", content)
  981. self.assertNotIn(b"id_rsa1", content)