test_config.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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. try:
  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. finally:
  300. # Clean up
  301. os.unlink(temp_path)
  302. def test_write_to_path_pathlib(self) -> None:
  303. import tempfile
  304. from pathlib import Path
  305. # Create a config
  306. cf = ConfigFile()
  307. cf.set((b"user",), b"name", b"Test User")
  308. # Write to pathlib.Path
  309. with tempfile.NamedTemporaryFile(suffix=".config", delete=False) as f:
  310. temp_path = f.name
  311. try:
  312. path_obj = Path(temp_path)
  313. cf.write_to_path(path_obj)
  314. # Read it back
  315. cf2 = ConfigFile.from_path(path_obj)
  316. self.assertEqual(cf2.get((b"user",), b"name"), b"Test User")
  317. finally:
  318. # Clean up
  319. os.unlink(temp_path)
  320. def test_include_basic(self) -> None:
  321. """Test basic include functionality."""
  322. with tempfile.TemporaryDirectory() as tmpdir:
  323. # Create included config file
  324. included_path = os.path.join(tmpdir, "included.config")
  325. with open(included_path, "wb") as f:
  326. f.write(
  327. b"[user]\n name = Included User\n email = included@example.com\n"
  328. )
  329. # Create main config with include
  330. main_config = self.from_file(
  331. b"[user]\n name = Main User\n[include]\n path = included.config\n"
  332. )
  333. # Should not include anything without proper directory context
  334. self.assertEqual(b"Main User", main_config.get((b"user",), b"name"))
  335. with self.assertRaises(KeyError):
  336. main_config.get((b"user",), b"email")
  337. # Now test with proper file loading
  338. main_path = os.path.join(tmpdir, "main.config")
  339. with open(main_path, "wb") as f:
  340. f.write(
  341. b"[user]\n name = Main User\n[include]\n path = included.config\n"
  342. )
  343. # Load from path to get include functionality
  344. cf = ConfigFile.from_path(main_path)
  345. self.assertEqual(b"Included User", cf.get((b"user",), b"name"))
  346. self.assertEqual(b"included@example.com", cf.get((b"user",), b"email"))
  347. def test_include_absolute_path(self) -> None:
  348. """Test include with absolute path."""
  349. with tempfile.TemporaryDirectory() as tmpdir:
  350. # Use realpath to resolve any symlinks (important on macOS and Windows)
  351. tmpdir = os.path.realpath(tmpdir)
  352. # Create included config file
  353. included_path = os.path.join(tmpdir, "included.config")
  354. with open(included_path, "wb") as f:
  355. f.write(b"[core]\n bare = true\n")
  356. # Create main config with absolute include path
  357. main_path = os.path.join(tmpdir, "main.config")
  358. with open(main_path, "wb") as f:
  359. # Properly escape backslashes in Windows paths
  360. escaped_path = included_path.replace("\\", "\\\\")
  361. f.write(f"[include]\n path = {escaped_path}\n".encode())
  362. cf = ConfigFile.from_path(main_path)
  363. self.assertEqual(b"true", cf.get((b"core",), b"bare"))
  364. def test_includeif_gitdir_match(self) -> None:
  365. """Test includeIf with gitdir condition that matches."""
  366. with tempfile.TemporaryDirectory() as tmpdir:
  367. repo_dir = os.path.join(tmpdir, "myrepo")
  368. os.makedirs(repo_dir)
  369. # Use realpath to resolve any symlinks (important on macOS)
  370. repo_dir = os.path.realpath(repo_dir)
  371. # Create included config file
  372. included_path = os.path.join(tmpdir, "work.config")
  373. with open(included_path, "wb") as f:
  374. f.write(b"[user]\n email = work@example.com\n")
  375. # Create main config with includeIf
  376. main_path = os.path.join(tmpdir, "main.config")
  377. with open(main_path, "wb") as f:
  378. f.write(
  379. f'[includeIf "gitdir:{repo_dir}/"]\n path = work.config\n'.encode()
  380. )
  381. # Load with matching repo_dir
  382. cf = ConfigFile.from_path(main_path, repo_dir=repo_dir)
  383. self.assertEqual(b"work@example.com", cf.get((b"user",), b"email"))
  384. def test_includeif_gitdir_no_match(self) -> None:
  385. """Test includeIf with gitdir condition that doesn't match."""
  386. with tempfile.TemporaryDirectory() as tmpdir:
  387. repo_dir = os.path.join(tmpdir, "myrepo")
  388. other_dir = os.path.join(tmpdir, "other")
  389. os.makedirs(repo_dir)
  390. os.makedirs(other_dir)
  391. # Use realpath to resolve any symlinks (important on macOS)
  392. repo_dir = os.path.realpath(repo_dir)
  393. other_dir = os.path.realpath(other_dir)
  394. # Create included config file
  395. included_path = os.path.join(tmpdir, "work.config")
  396. with open(included_path, "wb") as f:
  397. f.write(b"[user]\n email = work@example.com\n")
  398. # Create main config with includeIf
  399. main_path = os.path.join(tmpdir, "main.config")
  400. with open(main_path, "wb") as f:
  401. f.write(
  402. f'[includeIf "gitdir:{repo_dir}/"]\n path = work.config\n'.encode()
  403. )
  404. # Load with non-matching repo_dir
  405. cf = ConfigFile.from_path(main_path, repo_dir=other_dir)
  406. with self.assertRaises(KeyError):
  407. cf.get((b"user",), b"email")
  408. def test_includeif_gitdir_pattern(self) -> None:
  409. """Test includeIf with gitdir pattern matching."""
  410. with tempfile.TemporaryDirectory() as tmpdir:
  411. # Use realpath to resolve any symlinks
  412. tmpdir = os.path.realpath(tmpdir)
  413. work_dir = os.path.join(tmpdir, "work", "project1")
  414. os.makedirs(work_dir)
  415. # Create included config file
  416. included_path = os.path.join(tmpdir, "work.config")
  417. with open(included_path, "wb") as f:
  418. f.write(b"[user]\n email = work@company.com\n")
  419. # Create main config with pattern
  420. main_path = os.path.join(tmpdir, "main.config")
  421. with open(main_path, "wb") as f:
  422. # Pattern that should match any repo under work/
  423. f.write(b'[includeIf "gitdir:work/**"]\n path = work.config\n')
  424. # Load with matching pattern
  425. cf = ConfigFile.from_path(main_path, repo_dir=work_dir)
  426. self.assertEqual(b"work@company.com", cf.get((b"user",), b"email"))
  427. def test_include_circular(self) -> None:
  428. """Test that circular includes are handled properly."""
  429. with tempfile.TemporaryDirectory() as tmpdir:
  430. # Create two configs that include each other
  431. config1_path = os.path.join(tmpdir, "config1")
  432. config2_path = os.path.join(tmpdir, "config2")
  433. with open(config1_path, "wb") as f:
  434. f.write(b"[user]\n name = User1\n[include]\n path = config2\n")
  435. with open(config2_path, "wb") as f:
  436. f.write(
  437. b"[user]\n email = user2@example.com\n[include]\n path = config1\n"
  438. )
  439. # Should handle circular includes gracefully
  440. cf = ConfigFile.from_path(config1_path)
  441. self.assertEqual(b"User1", cf.get((b"user",), b"name"))
  442. self.assertEqual(b"user2@example.com", cf.get((b"user",), b"email"))
  443. def test_include_missing_file(self) -> None:
  444. """Test that missing include files are ignored."""
  445. with tempfile.TemporaryDirectory() as tmpdir:
  446. # Create config with include of non-existent file
  447. config_path = os.path.join(tmpdir, "config")
  448. with open(config_path, "wb") as f:
  449. f.write(
  450. b"[user]\n name = TestUser\n[include]\n path = missing.config\n"
  451. )
  452. # Should not fail, just ignore missing include
  453. cf = ConfigFile.from_path(config_path)
  454. self.assertEqual(b"TestUser", cf.get((b"user",), b"name"))
  455. def test_include_depth_limit(self) -> None:
  456. """Test that excessive include depth is prevented."""
  457. with tempfile.TemporaryDirectory() as tmpdir:
  458. # Create a chain of includes that exceeds depth limit
  459. for i in range(15):
  460. config_path = os.path.join(tmpdir, f"config{i}")
  461. with open(config_path, "wb") as f:
  462. if i == 0:
  463. f.write(b"[user]\n name = User0\n")
  464. f.write(f"[include]\n path = config{i + 1}\n".encode())
  465. # Should raise error due to depth limit
  466. with self.assertRaises(ValueError) as cm:
  467. ConfigFile.from_path(os.path.join(tmpdir, "config0"))
  468. self.assertIn("include depth", str(cm.exception))
  469. def test_include_with_custom_file_opener(self) -> None:
  470. """Test include functionality with a custom file opener for security."""
  471. with tempfile.TemporaryDirectory() as tmpdir:
  472. # Create config files
  473. included_path = os.path.join(tmpdir, "included.config")
  474. with open(included_path, "wb") as f:
  475. f.write(b"[user]\n email = custom@example.com\n")
  476. restricted_path = os.path.join(tmpdir, "restricted.config")
  477. with open(restricted_path, "wb") as f:
  478. f.write(b"[user]\n email = restricted@example.com\n")
  479. main_path = os.path.join(tmpdir, "main.config")
  480. with open(main_path, "wb") as f:
  481. f.write(b"[user]\n name = Test User\n")
  482. f.write(b"[include]\n path = included.config\n")
  483. f.write(b"[include]\n path = restricted.config\n")
  484. # Define a custom file opener that restricts access
  485. allowed_files = {included_path, main_path}
  486. def secure_file_opener(path):
  487. path_str = os.fspath(path)
  488. if path_str not in allowed_files:
  489. raise PermissionError(f"Access denied to {path}")
  490. return open(path_str, "rb")
  491. # Load config with restricted file access
  492. cf = ConfigFile.from_path(main_path, file_opener=secure_file_opener)
  493. # Should have the main config and included config, but not restricted
  494. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  495. self.assertEqual(b"custom@example.com", cf.get((b"user",), b"email"))
  496. # Email from restricted.config should not be loaded
  497. def test_unknown_includeif_condition(self) -> None:
  498. """Test that unknown includeIf conditions are silently ignored (like Git)."""
  499. with tempfile.TemporaryDirectory() as tmpdir:
  500. # Create included config file
  501. included_path = os.path.join(tmpdir, "included.config")
  502. with open(included_path, "wb") as f:
  503. f.write(b"[user]\n email = included@example.com\n")
  504. # Create main config with unknown includeIf condition
  505. main_path = os.path.join(tmpdir, "main.config")
  506. with open(main_path, "wb") as f:
  507. f.write(b"[user]\n name = Main User\n")
  508. f.write(
  509. b'[includeIf "unknowncondition:foo"]\n path = included.config\n'
  510. )
  511. # Should not fail, just ignore the unknown condition
  512. cf = ConfigFile.from_path(main_path)
  513. self.assertEqual(b"Main User", cf.get((b"user",), b"name"))
  514. # Email should not be included because condition is unknown
  515. with self.assertRaises(KeyError):
  516. cf.get((b"user",), b"email")
  517. def test_missing_include_file_logging(self) -> None:
  518. """Test that missing include files are logged but don't cause failure."""
  519. import logging
  520. from io import StringIO
  521. # Set up logging capture
  522. log_capture = StringIO()
  523. handler = logging.StreamHandler(log_capture)
  524. handler.setLevel(logging.DEBUG)
  525. logger = logging.getLogger("dulwich.config")
  526. logger.addHandler(handler)
  527. logger.setLevel(logging.DEBUG)
  528. try:
  529. with tempfile.TemporaryDirectory() as tmpdir:
  530. config_path = os.path.join(tmpdir, "test.config")
  531. with open(config_path, "wb") as f:
  532. f.write(b"[user]\n name = Test User\n")
  533. f.write(b"[include]\n path = nonexistent.config\n")
  534. # Should not fail, just log
  535. cf = ConfigFile.from_path(config_path)
  536. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  537. # Check that it was logged
  538. log_output = log_capture.getvalue()
  539. self.assertIn("Failed to read include file", log_output)
  540. self.assertIn("nonexistent.config", log_output)
  541. finally:
  542. logger.removeHandler(handler)
  543. def test_invalid_include_path_logging(self) -> None:
  544. """Test that invalid include paths are logged but don't cause failure."""
  545. import logging
  546. from io import StringIO
  547. # Set up logging capture
  548. log_capture = StringIO()
  549. handler = logging.StreamHandler(log_capture)
  550. handler.setLevel(logging.DEBUG)
  551. logger = logging.getLogger("dulwich.config")
  552. logger.addHandler(handler)
  553. logger.setLevel(logging.DEBUG)
  554. try:
  555. with tempfile.TemporaryDirectory() as tmpdir:
  556. config_path = os.path.join(tmpdir, "test.config")
  557. with open(config_path, "wb") as f:
  558. f.write(b"[user]\n name = Test User\n")
  559. # Use null bytes which are invalid in paths
  560. f.write(b"[include]\n path = /invalid\x00path/file.config\n")
  561. # Should not fail, just log
  562. cf = ConfigFile.from_path(config_path)
  563. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  564. # Check that it was logged
  565. log_output = log_capture.getvalue()
  566. self.assertIn("Invalid include path", log_output)
  567. finally:
  568. logger.removeHandler(handler)
  569. def test_unknown_includeif_condition_logging(self) -> None:
  570. """Test that unknown includeIf conditions are logged."""
  571. import logging
  572. from io import StringIO
  573. # Set up logging capture
  574. log_capture = StringIO()
  575. handler = logging.StreamHandler(log_capture)
  576. handler.setLevel(logging.DEBUG)
  577. logger = logging.getLogger("dulwich.config")
  578. logger.addHandler(handler)
  579. logger.setLevel(logging.DEBUG)
  580. try:
  581. with tempfile.TemporaryDirectory() as tmpdir:
  582. config_path = os.path.join(tmpdir, "test.config")
  583. with open(config_path, "wb") as f:
  584. f.write(b"[user]\n name = Test User\n")
  585. f.write(
  586. b'[includeIf "futurefeature:value"]\n path = other.config\n'
  587. )
  588. # Should not fail, just log
  589. cf = ConfigFile.from_path(config_path)
  590. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  591. # Check that it was logged
  592. log_output = log_capture.getvalue()
  593. self.assertIn("Unknown includeIf condition", log_output)
  594. self.assertIn("futurefeature:value", log_output)
  595. finally:
  596. logger.removeHandler(handler)
  597. def test_includeif_with_custom_file_opener(self) -> None:
  598. """Test includeIf functionality with custom file opener."""
  599. with tempfile.TemporaryDirectory() as tmpdir:
  600. # Use realpath to resolve any symlinks
  601. tmpdir = os.path.realpath(tmpdir)
  602. repo_dir = os.path.join(tmpdir, "work", "project", ".git")
  603. os.makedirs(repo_dir, exist_ok=True)
  604. # Create config files
  605. work_config_path = os.path.join(tmpdir, "work.config")
  606. with open(work_config_path, "wb") as f:
  607. f.write(b"[user]\n email = work@company.com\n")
  608. personal_config_path = os.path.join(tmpdir, "personal.config")
  609. with open(personal_config_path, "wb") as f:
  610. f.write(b"[user]\n email = personal@home.com\n")
  611. main_path = os.path.join(tmpdir, "main.config")
  612. with open(main_path, "wb") as f:
  613. f.write(b"[user]\n name = Test User\n")
  614. f.write(b'[includeIf "gitdir:**/work/**"]\n')
  615. escaped_work_path = work_config_path.replace("\\", "\\\\")
  616. f.write(f" path = {escaped_work_path}\n".encode())
  617. f.write(b'[includeIf "gitdir:**/personal/**"]\n')
  618. escaped_personal_path = personal_config_path.replace("\\", "\\\\")
  619. f.write(f" path = {escaped_personal_path}\n".encode())
  620. # Track which files were opened
  621. opened_files = []
  622. def tracking_file_opener(path):
  623. path_str = os.fspath(path)
  624. opened_files.append(path_str)
  625. return open(path_str, "rb")
  626. # Load config with tracking file opener
  627. cf = ConfigFile.from_path(
  628. main_path, repo_dir=repo_dir, file_opener=tracking_file_opener
  629. )
  630. # Check results
  631. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  632. self.assertEqual(b"work@company.com", cf.get((b"user",), b"email"))
  633. # Verify that only the matching includeIf file was opened
  634. self.assertIn(main_path, opened_files)
  635. self.assertIn(work_config_path, opened_files)
  636. self.assertNotIn(personal_config_path, opened_files)
  637. def test_custom_file_opener_with_include_depth(self) -> None:
  638. """Test that custom file opener is passed through include chain."""
  639. with tempfile.TemporaryDirectory() as tmpdir:
  640. # Use realpath to resolve any symlinks
  641. tmpdir = os.path.realpath(tmpdir)
  642. # Create a chain of includes
  643. final_config = os.path.join(tmpdir, "final.config")
  644. with open(final_config, "wb") as f:
  645. f.write(b"[feature]\n enabled = true\n")
  646. middle_config = os.path.join(tmpdir, "middle.config")
  647. with open(middle_config, "wb") as f:
  648. f.write(b"[user]\n email = test@example.com\n")
  649. escaped_final_config = final_config.replace("\\", "\\\\")
  650. f.write(f"[include]\n path = {escaped_final_config}\n".encode())
  651. main_config = os.path.join(tmpdir, "main.config")
  652. with open(main_config, "wb") as f:
  653. f.write(b"[user]\n name = Test User\n")
  654. escaped_middle_config = middle_config.replace("\\", "\\\\")
  655. f.write(f"[include]\n path = {escaped_middle_config}\n".encode())
  656. # Track file access order
  657. access_order = []
  658. def ordering_file_opener(path):
  659. path_str = os.fspath(path)
  660. access_order.append(os.path.basename(path_str))
  661. return open(path_str, "rb")
  662. # Load config
  663. cf = ConfigFile.from_path(main_config, file_opener=ordering_file_opener)
  664. # Verify all values were loaded
  665. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  666. self.assertEqual(b"test@example.com", cf.get((b"user",), b"email"))
  667. self.assertEqual(b"true", cf.get((b"feature",), b"enabled"))
  668. # Verify access order
  669. self.assertEqual(
  670. ["main.config", "middle.config", "final.config"], access_order
  671. )
  672. class ConfigDictTests(TestCase):
  673. def test_get_set(self) -> None:
  674. cd = ConfigDict()
  675. self.assertRaises(KeyError, cd.get, b"foo", b"core")
  676. cd.set((b"core",), b"foo", b"bla")
  677. self.assertEqual(b"bla", cd.get((b"core",), b"foo"))
  678. cd.set((b"core",), b"foo", b"bloe")
  679. self.assertEqual(b"bloe", cd.get((b"core",), b"foo"))
  680. def test_get_boolean(self) -> None:
  681. cd = ConfigDict()
  682. cd.set((b"core",), b"foo", b"true")
  683. self.assertTrue(cd.get_boolean((b"core",), b"foo"))
  684. cd.set((b"core",), b"foo", b"false")
  685. self.assertFalse(cd.get_boolean((b"core",), b"foo"))
  686. cd.set((b"core",), b"foo", b"invalid")
  687. self.assertRaises(ValueError, cd.get_boolean, (b"core",), b"foo")
  688. def test_dict(self) -> None:
  689. cd = ConfigDict()
  690. cd.set((b"core",), b"foo", b"bla")
  691. cd.set((b"core2",), b"foo", b"bloe")
  692. self.assertEqual([(b"core",), (b"core2",)], list(cd.keys()))
  693. self.assertEqual(cd[(b"core",)], {b"foo": b"bla"})
  694. cd[b"a"] = b"b"
  695. self.assertEqual(cd[b"a"], b"b")
  696. def test_items(self) -> None:
  697. cd = ConfigDict()
  698. cd.set((b"core",), b"foo", b"bla")
  699. cd.set((b"core2",), b"foo", b"bloe")
  700. self.assertEqual([(b"foo", b"bla")], list(cd.items((b"core",))))
  701. def test_items_nonexistant(self) -> None:
  702. cd = ConfigDict()
  703. cd.set((b"core2",), b"foo", b"bloe")
  704. self.assertEqual([], list(cd.items((b"core",))))
  705. def test_sections(self) -> None:
  706. cd = ConfigDict()
  707. cd.set((b"core2",), b"foo", b"bloe")
  708. self.assertEqual([(b"core2",)], list(cd.sections()))
  709. def test_set_vs_add(self) -> None:
  710. cd = ConfigDict()
  711. # Test add() creates multivars
  712. cd.add((b"core",), b"foo", b"value1")
  713. cd.add((b"core",), b"foo", b"value2")
  714. self.assertEqual(
  715. [b"value1", b"value2"], list(cd.get_multivar((b"core",), b"foo"))
  716. )
  717. # Test set() replaces values
  718. cd.set((b"core",), b"foo", b"value3")
  719. self.assertEqual([b"value3"], list(cd.get_multivar((b"core",), b"foo")))
  720. self.assertEqual(b"value3", cd.get((b"core",), b"foo"))
  721. class StackedConfigTests(TestCase):
  722. def test_default_backends(self) -> None:
  723. StackedConfig.default_backends()
  724. @skipIf(sys.platform != "win32", "Windows specific config location.")
  725. def test_windows_config_from_path(self) -> None:
  726. from dulwich.config import get_win_system_paths
  727. install_dir = os.path.join("C:", "foo", "Git")
  728. self.overrideEnv("PATH", os.path.join(install_dir, "cmd"))
  729. with patch("os.path.exists", return_value=True):
  730. paths = set(get_win_system_paths())
  731. self.assertEqual(
  732. {
  733. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  734. os.path.join(install_dir, "etc", "gitconfig"),
  735. },
  736. paths,
  737. )
  738. @skipIf(sys.platform != "win32", "Windows specific config location.")
  739. def test_windows_config_from_reg(self) -> None:
  740. import winreg
  741. from dulwich.config import get_win_system_paths
  742. self.overrideEnv("PATH", None)
  743. install_dir = os.path.join("C:", "foo", "Git")
  744. with patch("winreg.OpenKey"):
  745. with patch(
  746. "winreg.QueryValueEx",
  747. return_value=(install_dir, winreg.REG_SZ),
  748. ):
  749. paths = set(get_win_system_paths())
  750. self.assertEqual(
  751. {
  752. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  753. os.path.join(install_dir, "etc", "gitconfig"),
  754. },
  755. paths,
  756. )
  757. class EscapeValueTests(TestCase):
  758. def test_nothing(self) -> None:
  759. self.assertEqual(b"foo", _escape_value(b"foo"))
  760. def test_backslash(self) -> None:
  761. self.assertEqual(b"foo\\\\", _escape_value(b"foo\\"))
  762. def test_newline(self) -> None:
  763. self.assertEqual(b"foo\\n", _escape_value(b"foo\n"))
  764. class FormatStringTests(TestCase):
  765. def test_quoted(self) -> None:
  766. self.assertEqual(b'" foo"', _format_string(b" foo"))
  767. self.assertEqual(b'"\\tfoo"', _format_string(b"\tfoo"))
  768. def test_not_quoted(self) -> None:
  769. self.assertEqual(b"foo", _format_string(b"foo"))
  770. self.assertEqual(b"foo bar", _format_string(b"foo bar"))
  771. class ParseStringTests(TestCase):
  772. def test_quoted(self) -> None:
  773. self.assertEqual(b" foo", _parse_string(b'" foo"'))
  774. self.assertEqual(b"\tfoo", _parse_string(b'"\\tfoo"'))
  775. def test_not_quoted(self) -> None:
  776. self.assertEqual(b"foo", _parse_string(b"foo"))
  777. self.assertEqual(b"foo bar", _parse_string(b"foo bar"))
  778. def test_nothing(self) -> None:
  779. self.assertEqual(b"", _parse_string(b""))
  780. def test_tab(self) -> None:
  781. self.assertEqual(b"\tbar\t", _parse_string(b"\\tbar\\t"))
  782. def test_newline(self) -> None:
  783. self.assertEqual(b"\nbar\t", _parse_string(b"\\nbar\\t\t"))
  784. def test_quote(self) -> None:
  785. self.assertEqual(b'"foo"', _parse_string(b'\\"foo\\"'))
  786. class CheckVariableNameTests(TestCase):
  787. def test_invalid(self) -> None:
  788. self.assertFalse(_check_variable_name(b"foo "))
  789. self.assertFalse(_check_variable_name(b"bar,bar"))
  790. self.assertFalse(_check_variable_name(b"bar.bar"))
  791. def test_valid(self) -> None:
  792. self.assertTrue(_check_variable_name(b"FOO"))
  793. self.assertTrue(_check_variable_name(b"foo"))
  794. self.assertTrue(_check_variable_name(b"foo-bar"))
  795. class CheckSectionNameTests(TestCase):
  796. def test_invalid(self) -> None:
  797. self.assertFalse(_check_section_name(b"foo "))
  798. self.assertFalse(_check_section_name(b"bar,bar"))
  799. def test_valid(self) -> None:
  800. self.assertTrue(_check_section_name(b"FOO"))
  801. self.assertTrue(_check_section_name(b"foo"))
  802. self.assertTrue(_check_section_name(b"foo-bar"))
  803. self.assertTrue(_check_section_name(b"bar.bar"))
  804. class SubmodulesTests(TestCase):
  805. def testSubmodules(self) -> None:
  806. cf = ConfigFile.from_file(
  807. BytesIO(
  808. b"""\
  809. [submodule "core/lib"]
  810. \tpath = core/lib
  811. \turl = https://github.com/phhusson/QuasselC.git
  812. """
  813. )
  814. )
  815. got = list(parse_submodules(cf))
  816. self.assertEqual(
  817. [
  818. (
  819. b"core/lib",
  820. b"https://github.com/phhusson/QuasselC.git",
  821. b"core/lib",
  822. )
  823. ],
  824. got,
  825. )
  826. def testMalformedSubmodules(self) -> None:
  827. cf = ConfigFile.from_file(
  828. BytesIO(
  829. b"""\
  830. [submodule "core/lib"]
  831. \tpath = core/lib
  832. \turl = https://github.com/phhusson/QuasselC.git
  833. [submodule "dulwich"]
  834. \turl = https://github.com/jelmer/dulwich
  835. """
  836. )
  837. )
  838. got = list(parse_submodules(cf))
  839. self.assertEqual(
  840. [
  841. (
  842. b"core/lib",
  843. b"https://github.com/phhusson/QuasselC.git",
  844. b"core/lib",
  845. )
  846. ],
  847. got,
  848. )
  849. class ApplyInsteadOfTests(TestCase):
  850. def test_none(self) -> None:
  851. config = ConfigDict()
  852. self.assertEqual(
  853. "https://example.com/", apply_instead_of(config, "https://example.com/")
  854. )
  855. def test_apply(self) -> None:
  856. config = ConfigDict()
  857. config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  858. self.assertEqual(
  859. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  860. )
  861. def test_apply_multiple(self) -> None:
  862. config = ConfigDict()
  863. config.add(("url", "https://samba.org/"), "insteadOf", "https://blah.com/")
  864. config.add(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  865. self.assertEqual(
  866. [b"https://blah.com/", b"https://example.com/"],
  867. list(config.get_multivar(("url", "https://samba.org/"), "insteadOf")),
  868. )
  869. self.assertEqual(
  870. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  871. )
  872. def test_apply_preserves_case_in_subsection(self) -> None:
  873. """Test that mixed-case URLs (like those with access tokens) are preserved."""
  874. config = ConfigDict()
  875. # GitHub access tokens have mixed case that must be preserved
  876. url_with_token = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/"
  877. config.set(("url", url_with_token), "insteadOf", "https://github.com/")
  878. # Apply the substitution
  879. result = apply_instead_of(config, "https://github.com/jelmer/dulwich.git")
  880. expected = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/jelmer/dulwich.git"
  881. self.assertEqual(expected, result)
  882. # Verify the token case is preserved
  883. self.assertIn("ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890", result)
  884. class CaseInsensitiveConfigTests(TestCase):
  885. def test_case_insensitive(self) -> None:
  886. config = CaseInsensitiveOrderedMultiDict()
  887. config[("core",)] = "value"
  888. self.assertEqual("value", config[("CORE",)])
  889. self.assertEqual("value", config[("CoRe",)])
  890. self.assertEqual([("core",)], list(config.keys()))
  891. def test_multiple_set(self) -> None:
  892. config = CaseInsensitiveOrderedMultiDict()
  893. config[("core",)] = "value1"
  894. config[("core",)] = "value2"
  895. # The second set overwrites the first one
  896. self.assertEqual("value2", config[("core",)])
  897. self.assertEqual("value2", config[("CORE",)])
  898. def test_get_all(self) -> None:
  899. config = CaseInsensitiveOrderedMultiDict()
  900. config[("core",)] = "value1"
  901. config[("CORE",)] = "value2"
  902. config[("CoRe",)] = "value3"
  903. self.assertEqual(
  904. ["value1", "value2", "value3"], list(config.get_all(("core",)))
  905. )
  906. self.assertEqual(
  907. ["value1", "value2", "value3"], list(config.get_all(("CORE",)))
  908. )
  909. def test_delitem(self) -> None:
  910. config = CaseInsensitiveOrderedMultiDict()
  911. config[("core",)] = "value1"
  912. config[("CORE",)] = "value2"
  913. config[("other",)] = "value3"
  914. del config[("core",)]
  915. self.assertNotIn(("core",), config)
  916. self.assertNotIn(("CORE",), config)
  917. self.assertEqual("value3", config[("other",)])
  918. self.assertEqual(1, len(config))
  919. def test_len(self) -> None:
  920. config = CaseInsensitiveOrderedMultiDict()
  921. self.assertEqual(0, len(config))
  922. config[("core",)] = "value1"
  923. self.assertEqual(1, len(config))
  924. config[("CORE",)] = "value2"
  925. self.assertEqual(1, len(config)) # Same key, case insensitive
  926. def test_subsection_case_preserved(self) -> None:
  927. """Test that subsection names preserve their case."""
  928. config = CaseInsensitiveOrderedMultiDict()
  929. # Section names should be case-insensitive, but subsection names should preserve case
  930. config[("url", "https://Example.COM/Path")] = "value1"
  931. # Can retrieve with different case section name
  932. self.assertEqual("value1", config[("URL", "https://Example.COM/Path")])
  933. self.assertEqual("value1", config[("url", "https://Example.COM/Path")])
  934. # But not with different case subsection name
  935. with self.assertRaises(KeyError):
  936. config[("url", "https://example.com/path")]
  937. # Verify the stored key preserves subsection case
  938. stored_keys = list(config.keys())
  939. self.assertEqual(1, len(stored_keys))
  940. self.assertEqual(("url", "https://Example.COM/Path"), stored_keys[0])
  941. config[("other",)] = "value3"
  942. self.assertEqual(2, len(config))
  943. def test_make_from_dict(self) -> None:
  944. original = {("core",): "value1", ("other",): "value2"}
  945. config = CaseInsensitiveOrderedMultiDict.make(original)
  946. self.assertEqual("value1", config[("core",)])
  947. self.assertEqual("value1", config[("CORE",)])
  948. self.assertEqual("value2", config[("other",)])
  949. def test_make_from_self(self) -> None:
  950. config1 = CaseInsensitiveOrderedMultiDict()
  951. config1[("core",)] = "value"
  952. config2 = CaseInsensitiveOrderedMultiDict.make(config1)
  953. self.assertIs(config1, config2)
  954. def test_make_invalid_type(self) -> None:
  955. self.assertRaises(TypeError, CaseInsensitiveOrderedMultiDict.make, "invalid")
  956. def test_get_with_default(self) -> None:
  957. config = CaseInsensitiveOrderedMultiDict()
  958. config[("core",)] = "value"
  959. self.assertEqual("value", config.get(("core",)))
  960. self.assertEqual("value", config.get(("CORE",)))
  961. self.assertEqual("default", config.get(("missing",), "default"))
  962. # Test SENTINEL behavior
  963. result = config.get(("missing",))
  964. self.assertIsInstance(result, CaseInsensitiveOrderedMultiDict)
  965. self.assertEqual(0, len(result))
  966. def test_setdefault(self) -> None:
  967. config = CaseInsensitiveOrderedMultiDict()
  968. # Set new value
  969. result1 = config.setdefault(("core",), "value1")
  970. self.assertEqual("value1", result1)
  971. self.assertEqual("value1", config[("core",)])
  972. # Try to set again with different case - should return existing
  973. result2 = config.setdefault(("CORE",), "value2")
  974. self.assertEqual("value1", result2)
  975. self.assertEqual("value1", config[("core",)])
  976. def test_values(self) -> None:
  977. config = CaseInsensitiveOrderedMultiDict()
  978. config[("core",)] = "value1"
  979. config[("other",)] = "value2"
  980. config[("CORE",)] = "value3" # Overwrites previous core value
  981. self.assertEqual({"value3", "value2"}, set(config.values()))
  982. def test_items_iteration(self) -> None:
  983. config = CaseInsensitiveOrderedMultiDict()
  984. config[("core",)] = "value1"
  985. config[("other",)] = "value2"
  986. config[("CORE",)] = "value3"
  987. items = list(config.items())
  988. self.assertEqual(3, len(items))
  989. self.assertEqual((("core",), "value1"), items[0])
  990. self.assertEqual((("other",), "value2"), items[1])
  991. self.assertEqual((("CORE",), "value3"), items[2])
  992. def test_str_keys(self) -> None:
  993. config = CaseInsensitiveOrderedMultiDict()
  994. config["core"] = "value"
  995. self.assertEqual("value", config["CORE"])
  996. self.assertEqual("value", config["CoRe"])
  997. def test_nested_tuple_keys(self) -> None:
  998. config = CaseInsensitiveOrderedMultiDict()
  999. config[("branch", "master")] = "value"
  1000. # Section names are case-insensitive
  1001. self.assertEqual("value", config[("BRANCH", "master")])
  1002. self.assertEqual("value", config[("Branch", "master")])
  1003. # But subsection names are case-sensitive
  1004. with self.assertRaises(KeyError):
  1005. config[("branch", "MASTER")]
  1006. class ConfigFileSetTests(TestCase):
  1007. def test_set_replaces_value(self) -> None:
  1008. # Test that set() replaces the value instead of appending
  1009. cf = ConfigFile()
  1010. cf.set((b"core",), b"sshCommand", b"ssh -i ~/.ssh/id_rsa1")
  1011. cf.set((b"core",), b"sshCommand", b"ssh -i ~/.ssh/id_rsa2")
  1012. # Should only have one value
  1013. self.assertEqual(b"ssh -i ~/.ssh/id_rsa2", cf.get((b"core",), b"sshCommand"))
  1014. # When written to file, should only have one entry
  1015. f = BytesIO()
  1016. cf.write_to_file(f)
  1017. content = f.getvalue()
  1018. self.assertEqual(1, content.count(b"sshCommand"))
  1019. self.assertIn(b"sshCommand = ssh -i ~/.ssh/id_rsa2", content)
  1020. self.assertNotIn(b"id_rsa1", content)