test_config.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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_hasconfig(self) -> None:
  365. """Test includeIf with hasconfig conditions."""
  366. with tempfile.TemporaryDirectory() as tmpdir:
  367. # Create included config file
  368. work_included_path = os.path.join(tmpdir, "work.config")
  369. with open(work_included_path, "wb") as f:
  370. f.write(b"[user]\n email = work@company.com\n")
  371. personal_included_path = os.path.join(tmpdir, "personal.config")
  372. with open(personal_included_path, "wb") as f:
  373. f.write(b"[user]\n email = personal@example.com\n")
  374. # Create main config with hasconfig conditions
  375. main_path = os.path.join(tmpdir, "main.config")
  376. with open(main_path, "wb") as f:
  377. f.write(
  378. b'[remote "origin"]\n'
  379. b" url = ssh://org-work@github.com/company/project\n"
  380. b'[includeIf "hasconfig:remote.*.url:ssh://org-*@github.com/**"]\n'
  381. b" path = work.config\n"
  382. b'[includeIf "hasconfig:remote.*.url:https://github.com/opensource/**"]\n'
  383. b" path = personal.config\n"
  384. )
  385. # Load config - should match the work config due to org-work remote
  386. # The second condition won't match since url doesn't have /opensource/ path
  387. cf = ConfigFile.from_path(main_path)
  388. self.assertEqual(b"work@company.com", cf.get((b"user",), b"email"))
  389. def test_includeif_hasconfig_wildcard(self) -> None:
  390. """Test includeIf hasconfig with wildcard patterns."""
  391. with tempfile.TemporaryDirectory() as tmpdir:
  392. # Create included config
  393. included_path = os.path.join(tmpdir, "included.config")
  394. with open(included_path, "wb") as f:
  395. f.write(b"[user]\n name = IncludedUser\n")
  396. # Create main config with hasconfig condition using wildcards
  397. main_path = os.path.join(tmpdir, "main.config")
  398. with open(main_path, "wb") as f:
  399. f.write(
  400. b"[core]\n"
  401. b" autocrlf = true\n"
  402. b'[includeIf "hasconfig:core.autocrlf:true"]\n'
  403. b" path = included.config\n"
  404. )
  405. # Load config - should include based on core.autocrlf value
  406. cf = ConfigFile.from_path(main_path)
  407. self.assertEqual(b"IncludedUser", cf.get((b"user",), b"name"))
  408. def test_includeif_hasconfig_no_match(self) -> None:
  409. """Test includeIf hasconfig when condition doesn't match."""
  410. with tempfile.TemporaryDirectory() as tmpdir:
  411. # Create included config
  412. included_path = os.path.join(tmpdir, "included.config")
  413. with open(included_path, "wb") as f:
  414. f.write(b"[user]\n name = IncludedUser\n")
  415. # Create main config with non-matching hasconfig condition
  416. main_path = os.path.join(tmpdir, "main.config")
  417. with open(main_path, "wb") as f:
  418. f.write(
  419. b"[core]\n"
  420. b" autocrlf = false\n"
  421. b'[includeIf "hasconfig:core.autocrlf:true"]\n'
  422. b" path = included.config\n"
  423. )
  424. # Load config - should NOT include since condition doesn't match
  425. cf = ConfigFile.from_path(main_path)
  426. with self.assertRaises(KeyError):
  427. cf.get((b"user",), b"name")
  428. def test_include_circular(self) -> None:
  429. """Test that circular includes are handled properly."""
  430. with tempfile.TemporaryDirectory() as tmpdir:
  431. # Create two configs that include each other
  432. config1_path = os.path.join(tmpdir, "config1")
  433. config2_path = os.path.join(tmpdir, "config2")
  434. with open(config1_path, "wb") as f:
  435. f.write(b"[user]\n name = User1\n[include]\n path = config2\n")
  436. with open(config2_path, "wb") as f:
  437. f.write(
  438. b"[user]\n email = user2@example.com\n[include]\n path = config1\n"
  439. )
  440. # Should handle circular includes gracefully
  441. cf = ConfigFile.from_path(config1_path)
  442. self.assertEqual(b"User1", cf.get((b"user",), b"name"))
  443. self.assertEqual(b"user2@example.com", cf.get((b"user",), b"email"))
  444. def test_include_missing_file(self) -> None:
  445. """Test that missing include files are ignored."""
  446. with tempfile.TemporaryDirectory() as tmpdir:
  447. # Create config with include of non-existent file
  448. config_path = os.path.join(tmpdir, "config")
  449. with open(config_path, "wb") as f:
  450. f.write(
  451. b"[user]\n name = TestUser\n[include]\n path = missing.config\n"
  452. )
  453. # Should not fail, just ignore missing include
  454. cf = ConfigFile.from_path(config_path)
  455. self.assertEqual(b"TestUser", cf.get((b"user",), b"name"))
  456. def test_include_depth_limit(self) -> None:
  457. """Test that excessive include depth is prevented."""
  458. with tempfile.TemporaryDirectory() as tmpdir:
  459. # Create a chain of includes that exceeds depth limit
  460. for i in range(15):
  461. config_path = os.path.join(tmpdir, f"config{i}")
  462. with open(config_path, "wb") as f:
  463. if i == 0:
  464. f.write(b"[user]\n name = User0\n")
  465. f.write(f"[include]\n path = config{i + 1}\n".encode())
  466. # Should raise error due to depth limit
  467. with self.assertRaises(ValueError) as cm:
  468. ConfigFile.from_path(os.path.join(tmpdir, "config0"))
  469. self.assertIn("include depth", str(cm.exception))
  470. def test_include_with_custom_file_opener(self) -> None:
  471. """Test include functionality with a custom file opener for security."""
  472. with tempfile.TemporaryDirectory() as tmpdir:
  473. # Create config files
  474. included_path = os.path.join(tmpdir, "included.config")
  475. with open(included_path, "wb") as f:
  476. f.write(b"[user]\n email = custom@example.com\n")
  477. restricted_path = os.path.join(tmpdir, "restricted.config")
  478. with open(restricted_path, "wb") as f:
  479. f.write(b"[user]\n email = restricted@example.com\n")
  480. main_path = os.path.join(tmpdir, "main.config")
  481. with open(main_path, "wb") as f:
  482. f.write(b"[user]\n name = Test User\n")
  483. f.write(b"[include]\n path = included.config\n")
  484. f.write(b"[include]\n path = restricted.config\n")
  485. # Define a custom file opener that restricts access
  486. allowed_files = {included_path, main_path}
  487. def secure_file_opener(path):
  488. path_str = os.fspath(path)
  489. if path_str not in allowed_files:
  490. raise PermissionError(f"Access denied to {path}")
  491. return open(path_str, "rb")
  492. # Load config with restricted file access
  493. cf = ConfigFile.from_path(main_path, file_opener=secure_file_opener)
  494. # Should have the main config and included config, but not restricted
  495. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  496. self.assertEqual(b"custom@example.com", cf.get((b"user",), b"email"))
  497. # Email from restricted.config should not be loaded
  498. def test_unknown_includeif_condition(self) -> None:
  499. """Test that unknown includeIf conditions are silently ignored (like Git)."""
  500. with tempfile.TemporaryDirectory() as tmpdir:
  501. # Create included config file
  502. included_path = os.path.join(tmpdir, "included.config")
  503. with open(included_path, "wb") as f:
  504. f.write(b"[user]\n email = included@example.com\n")
  505. # Create main config with unknown includeIf condition
  506. main_path = os.path.join(tmpdir, "main.config")
  507. with open(main_path, "wb") as f:
  508. f.write(b"[user]\n name = Main User\n")
  509. f.write(
  510. b'[includeIf "unknowncondition:foo"]\n path = included.config\n'
  511. )
  512. # Should not fail, just ignore the unknown condition
  513. cf = ConfigFile.from_path(main_path)
  514. self.assertEqual(b"Main User", cf.get((b"user",), b"name"))
  515. # Email should not be included because condition is unknown
  516. with self.assertRaises(KeyError):
  517. cf.get((b"user",), b"email")
  518. def test_missing_include_file_logging(self) -> None:
  519. """Test that missing include files are logged but don't cause failure."""
  520. import logging
  521. from io import StringIO
  522. # Set up logging capture
  523. log_capture = StringIO()
  524. handler = logging.StreamHandler(log_capture)
  525. handler.setLevel(logging.DEBUG)
  526. logger = logging.getLogger("dulwich.config")
  527. logger.addHandler(handler)
  528. logger.setLevel(logging.DEBUG)
  529. try:
  530. with tempfile.TemporaryDirectory() as tmpdir:
  531. config_path = os.path.join(tmpdir, "test.config")
  532. with open(config_path, "wb") as f:
  533. f.write(b"[user]\n name = Test User\n")
  534. f.write(b"[include]\n path = nonexistent.config\n")
  535. # Should not fail, just log
  536. cf = ConfigFile.from_path(config_path)
  537. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  538. # Check that it was logged
  539. log_output = log_capture.getvalue()
  540. self.assertIn("Invalid include path", log_output)
  541. self.assertIn("nonexistent.config", log_output)
  542. finally:
  543. logger.removeHandler(handler)
  544. def test_invalid_include_path_logging(self) -> None:
  545. """Test that invalid include paths are logged but don't cause failure."""
  546. import logging
  547. from io import StringIO
  548. # Set up logging capture
  549. log_capture = StringIO()
  550. handler = logging.StreamHandler(log_capture)
  551. handler.setLevel(logging.DEBUG)
  552. logger = logging.getLogger("dulwich.config")
  553. logger.addHandler(handler)
  554. logger.setLevel(logging.DEBUG)
  555. try:
  556. with tempfile.TemporaryDirectory() as tmpdir:
  557. config_path = os.path.join(tmpdir, "test.config")
  558. with open(config_path, "wb") as f:
  559. f.write(b"[user]\n name = Test User\n")
  560. # Use null bytes which are invalid in paths
  561. f.write(b"[include]\n path = /invalid\x00path/file.config\n")
  562. # Should not fail, just log
  563. cf = ConfigFile.from_path(config_path)
  564. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  565. # Check that it was logged
  566. log_output = log_capture.getvalue()
  567. self.assertIn("Invalid include path", log_output)
  568. finally:
  569. logger.removeHandler(handler)
  570. def test_unknown_includeif_condition_logging(self) -> None:
  571. """Test that unknown includeIf conditions are logged."""
  572. import logging
  573. from io import StringIO
  574. # Set up logging capture
  575. log_capture = StringIO()
  576. handler = logging.StreamHandler(log_capture)
  577. handler.setLevel(logging.DEBUG)
  578. logger = logging.getLogger("dulwich.config")
  579. logger.addHandler(handler)
  580. logger.setLevel(logging.DEBUG)
  581. try:
  582. with tempfile.TemporaryDirectory() as tmpdir:
  583. config_path = os.path.join(tmpdir, "test.config")
  584. with open(config_path, "wb") as f:
  585. f.write(b"[user]\n name = Test User\n")
  586. f.write(
  587. b'[includeIf "futurefeature:value"]\n path = other.config\n'
  588. )
  589. # Should not fail, just log
  590. cf = ConfigFile.from_path(config_path)
  591. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  592. # Check that it was logged
  593. log_output = log_capture.getvalue()
  594. self.assertIn("Unknown includeIf condition", log_output)
  595. self.assertIn("futurefeature:value", log_output)
  596. finally:
  597. logger.removeHandler(handler)
  598. def test_custom_file_opener_with_include_depth(self) -> None:
  599. """Test that custom file opener is passed through include chain."""
  600. with tempfile.TemporaryDirectory() as tmpdir:
  601. # Use realpath to resolve any symlinks
  602. tmpdir = os.path.realpath(tmpdir)
  603. # Create a chain of includes
  604. final_config = os.path.join(tmpdir, "final.config")
  605. with open(final_config, "wb") as f:
  606. f.write(b"[feature]\n enabled = true\n")
  607. middle_config = os.path.join(tmpdir, "middle.config")
  608. with open(middle_config, "wb") as f:
  609. f.write(b"[user]\n email = test@example.com\n")
  610. escaped_final_config = final_config.replace("\\", "\\\\")
  611. f.write(f"[include]\n path = {escaped_final_config}\n".encode())
  612. main_config = os.path.join(tmpdir, "main.config")
  613. with open(main_config, "wb") as f:
  614. f.write(b"[user]\n name = Test User\n")
  615. escaped_middle_config = middle_config.replace("\\", "\\\\")
  616. f.write(f"[include]\n path = {escaped_middle_config}\n".encode())
  617. # Track file access order
  618. access_order = []
  619. def ordering_file_opener(path):
  620. path_str = os.fspath(path)
  621. access_order.append(os.path.basename(path_str))
  622. return open(path_str, "rb")
  623. # Load config
  624. cf = ConfigFile.from_path(main_config, file_opener=ordering_file_opener)
  625. # Verify all values were loaded
  626. self.assertEqual(b"Test User", cf.get((b"user",), b"name"))
  627. self.assertEqual(b"test@example.com", cf.get((b"user",), b"email"))
  628. self.assertEqual(b"true", cf.get((b"feature",), b"enabled"))
  629. # Verify access order
  630. self.assertEqual(
  631. ["main.config", "middle.config", "final.config"], access_order
  632. )
  633. class ConfigDictTests(TestCase):
  634. def test_get_set(self) -> None:
  635. cd = ConfigDict()
  636. self.assertRaises(KeyError, cd.get, b"foo", b"core")
  637. cd.set((b"core",), b"foo", b"bla")
  638. self.assertEqual(b"bla", cd.get((b"core",), b"foo"))
  639. cd.set((b"core",), b"foo", b"bloe")
  640. self.assertEqual(b"bloe", cd.get((b"core",), b"foo"))
  641. def test_get_boolean(self) -> None:
  642. cd = ConfigDict()
  643. cd.set((b"core",), b"foo", b"true")
  644. self.assertTrue(cd.get_boolean((b"core",), b"foo"))
  645. cd.set((b"core",), b"foo", b"false")
  646. self.assertFalse(cd.get_boolean((b"core",), b"foo"))
  647. cd.set((b"core",), b"foo", b"invalid")
  648. self.assertRaises(ValueError, cd.get_boolean, (b"core",), b"foo")
  649. def test_dict(self) -> None:
  650. cd = ConfigDict()
  651. cd.set((b"core",), b"foo", b"bla")
  652. cd.set((b"core2",), b"foo", b"bloe")
  653. self.assertEqual([(b"core",), (b"core2",)], list(cd.keys()))
  654. self.assertEqual(cd[(b"core",)], {b"foo": b"bla"})
  655. cd[b"a"] = b"b"
  656. self.assertEqual(cd[b"a"], b"b")
  657. def test_items(self) -> None:
  658. cd = ConfigDict()
  659. cd.set((b"core",), b"foo", b"bla")
  660. cd.set((b"core2",), b"foo", b"bloe")
  661. self.assertEqual([(b"foo", b"bla")], list(cd.items((b"core",))))
  662. def test_items_nonexistant(self) -> None:
  663. cd = ConfigDict()
  664. cd.set((b"core2",), b"foo", b"bloe")
  665. self.assertEqual([], list(cd.items((b"core",))))
  666. def test_sections(self) -> None:
  667. cd = ConfigDict()
  668. cd.set((b"core2",), b"foo", b"bloe")
  669. self.assertEqual([(b"core2",)], list(cd.sections()))
  670. def test_set_vs_add(self) -> None:
  671. cd = ConfigDict()
  672. # Test add() creates multivars
  673. cd.add((b"core",), b"foo", b"value1")
  674. cd.add((b"core",), b"foo", b"value2")
  675. self.assertEqual(
  676. [b"value1", b"value2"], list(cd.get_multivar((b"core",), b"foo"))
  677. )
  678. # Test set() replaces values
  679. cd.set((b"core",), b"foo", b"value3")
  680. self.assertEqual([b"value3"], list(cd.get_multivar((b"core",), b"foo")))
  681. self.assertEqual(b"value3", cd.get((b"core",), b"foo"))
  682. class StackedConfigTests(TestCase):
  683. def test_default_backends(self) -> None:
  684. StackedConfig.default_backends()
  685. @skipIf(sys.platform != "win32", "Windows specific config location.")
  686. def test_windows_config_from_path(self) -> None:
  687. from dulwich.config import get_win_system_paths
  688. install_dir = os.path.join("C:", "foo", "Git")
  689. self.overrideEnv("PATH", os.path.join(install_dir, "cmd"))
  690. with patch("os.path.exists", return_value=True):
  691. paths = set(get_win_system_paths())
  692. self.assertEqual(
  693. {
  694. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  695. os.path.join(install_dir, "etc", "gitconfig"),
  696. },
  697. paths,
  698. )
  699. @skipIf(sys.platform != "win32", "Windows specific config location.")
  700. def test_windows_config_from_reg(self) -> None:
  701. import winreg
  702. from dulwich.config import get_win_system_paths
  703. self.overrideEnv("PATH", None)
  704. install_dir = os.path.join("C:", "foo", "Git")
  705. with patch("winreg.OpenKey"):
  706. with patch(
  707. "winreg.QueryValueEx",
  708. return_value=(install_dir, winreg.REG_SZ),
  709. ):
  710. paths = set(get_win_system_paths())
  711. self.assertEqual(
  712. {
  713. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  714. os.path.join(install_dir, "etc", "gitconfig"),
  715. },
  716. paths,
  717. )
  718. class EscapeValueTests(TestCase):
  719. def test_nothing(self) -> None:
  720. self.assertEqual(b"foo", _escape_value(b"foo"))
  721. def test_backslash(self) -> None:
  722. self.assertEqual(b"foo\\\\", _escape_value(b"foo\\"))
  723. def test_newline(self) -> None:
  724. self.assertEqual(b"foo\\n", _escape_value(b"foo\n"))
  725. class FormatStringTests(TestCase):
  726. def test_quoted(self) -> None:
  727. self.assertEqual(b'" foo"', _format_string(b" foo"))
  728. self.assertEqual(b'"\\tfoo"', _format_string(b"\tfoo"))
  729. def test_not_quoted(self) -> None:
  730. self.assertEqual(b"foo", _format_string(b"foo"))
  731. self.assertEqual(b"foo bar", _format_string(b"foo bar"))
  732. class ParseStringTests(TestCase):
  733. def test_quoted(self) -> None:
  734. self.assertEqual(b" foo", _parse_string(b'" foo"'))
  735. self.assertEqual(b"\tfoo", _parse_string(b'"\\tfoo"'))
  736. def test_not_quoted(self) -> None:
  737. self.assertEqual(b"foo", _parse_string(b"foo"))
  738. self.assertEqual(b"foo bar", _parse_string(b"foo bar"))
  739. def test_nothing(self) -> None:
  740. self.assertEqual(b"", _parse_string(b""))
  741. def test_tab(self) -> None:
  742. self.assertEqual(b"\tbar\t", _parse_string(b"\\tbar\\t"))
  743. def test_newline(self) -> None:
  744. self.assertEqual(b"\nbar\t", _parse_string(b"\\nbar\\t\t"))
  745. def test_quote(self) -> None:
  746. self.assertEqual(b'"foo"', _parse_string(b'\\"foo\\"'))
  747. class CheckVariableNameTests(TestCase):
  748. def test_invalid(self) -> None:
  749. self.assertFalse(_check_variable_name(b"foo "))
  750. self.assertFalse(_check_variable_name(b"bar,bar"))
  751. self.assertFalse(_check_variable_name(b"bar.bar"))
  752. def test_valid(self) -> None:
  753. self.assertTrue(_check_variable_name(b"FOO"))
  754. self.assertTrue(_check_variable_name(b"foo"))
  755. self.assertTrue(_check_variable_name(b"foo-bar"))
  756. class CheckSectionNameTests(TestCase):
  757. def test_invalid(self) -> None:
  758. self.assertFalse(_check_section_name(b"foo "))
  759. self.assertFalse(_check_section_name(b"bar,bar"))
  760. def test_valid(self) -> None:
  761. self.assertTrue(_check_section_name(b"FOO"))
  762. self.assertTrue(_check_section_name(b"foo"))
  763. self.assertTrue(_check_section_name(b"foo-bar"))
  764. self.assertTrue(_check_section_name(b"bar.bar"))
  765. class SubmodulesTests(TestCase):
  766. def testSubmodules(self) -> None:
  767. cf = ConfigFile.from_file(
  768. BytesIO(
  769. b"""\
  770. [submodule "core/lib"]
  771. \tpath = core/lib
  772. \turl = https://github.com/phhusson/QuasselC.git
  773. """
  774. )
  775. )
  776. got = list(parse_submodules(cf))
  777. self.assertEqual(
  778. [
  779. (
  780. b"core/lib",
  781. b"https://github.com/phhusson/QuasselC.git",
  782. b"core/lib",
  783. )
  784. ],
  785. got,
  786. )
  787. def testMalformedSubmodules(self) -> None:
  788. cf = ConfigFile.from_file(
  789. BytesIO(
  790. b"""\
  791. [submodule "core/lib"]
  792. \tpath = core/lib
  793. \turl = https://github.com/phhusson/QuasselC.git
  794. [submodule "dulwich"]
  795. \turl = https://github.com/jelmer/dulwich
  796. """
  797. )
  798. )
  799. got = list(parse_submodules(cf))
  800. self.assertEqual(
  801. [
  802. (
  803. b"core/lib",
  804. b"https://github.com/phhusson/QuasselC.git",
  805. b"core/lib",
  806. )
  807. ],
  808. got,
  809. )
  810. class ApplyInsteadOfTests(TestCase):
  811. def test_none(self) -> None:
  812. config = ConfigDict()
  813. self.assertEqual(
  814. "https://example.com/", apply_instead_of(config, "https://example.com/")
  815. )
  816. def test_apply(self) -> None:
  817. config = ConfigDict()
  818. config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  819. self.assertEqual(
  820. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  821. )
  822. def test_apply_multiple(self) -> None:
  823. config = ConfigDict()
  824. config.add(("url", "https://samba.org/"), "insteadOf", "https://blah.com/")
  825. config.add(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  826. self.assertEqual(
  827. [b"https://blah.com/", b"https://example.com/"],
  828. list(config.get_multivar(("url", "https://samba.org/"), "insteadOf")),
  829. )
  830. self.assertEqual(
  831. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  832. )
  833. def test_apply_preserves_case_in_subsection(self) -> None:
  834. """Test that mixed-case URLs (like those with access tokens) are preserved."""
  835. config = ConfigDict()
  836. # GitHub access tokens have mixed case that must be preserved
  837. url_with_token = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/"
  838. config.set(("url", url_with_token), "insteadOf", "https://github.com/")
  839. # Apply the substitution
  840. result = apply_instead_of(config, "https://github.com/jelmer/dulwich.git")
  841. expected = "https://ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890@github.com/jelmer/dulwich.git"
  842. self.assertEqual(expected, result)
  843. # Verify the token case is preserved
  844. self.assertIn("ghp_AbCdEfGhIjKlMnOpQrStUvWxYz1234567890", result)
  845. class CaseInsensitiveConfigTests(TestCase):
  846. def test_case_insensitive(self) -> None:
  847. config = CaseInsensitiveOrderedMultiDict()
  848. config[("core",)] = "value"
  849. self.assertEqual("value", config[("CORE",)])
  850. self.assertEqual("value", config[("CoRe",)])
  851. self.assertEqual([("core",)], list(config.keys()))
  852. def test_multiple_set(self) -> None:
  853. config = CaseInsensitiveOrderedMultiDict()
  854. config[("core",)] = "value1"
  855. config[("core",)] = "value2"
  856. # The second set overwrites the first one
  857. self.assertEqual("value2", config[("core",)])
  858. self.assertEqual("value2", config[("CORE",)])
  859. def test_get_all(self) -> None:
  860. config = CaseInsensitiveOrderedMultiDict()
  861. config[("core",)] = "value1"
  862. config[("CORE",)] = "value2"
  863. config[("CoRe",)] = "value3"
  864. self.assertEqual(
  865. ["value1", "value2", "value3"], list(config.get_all(("core",)))
  866. )
  867. self.assertEqual(
  868. ["value1", "value2", "value3"], list(config.get_all(("CORE",)))
  869. )
  870. def test_delitem(self) -> None:
  871. config = CaseInsensitiveOrderedMultiDict()
  872. config[("core",)] = "value1"
  873. config[("CORE",)] = "value2"
  874. config[("other",)] = "value3"
  875. del config[("core",)]
  876. self.assertNotIn(("core",), config)
  877. self.assertNotIn(("CORE",), config)
  878. self.assertEqual("value3", config[("other",)])
  879. self.assertEqual(1, len(config))
  880. def test_len(self) -> None:
  881. config = CaseInsensitiveOrderedMultiDict()
  882. self.assertEqual(0, len(config))
  883. config[("core",)] = "value1"
  884. self.assertEqual(1, len(config))
  885. config[("CORE",)] = "value2"
  886. self.assertEqual(1, len(config)) # Same key, case insensitive
  887. def test_subsection_case_preserved(self) -> None:
  888. """Test that subsection names preserve their case."""
  889. config = CaseInsensitiveOrderedMultiDict()
  890. # Section names should be case-insensitive, but subsection names should preserve case
  891. config[("url", "https://Example.COM/Path")] = "value1"
  892. # Can retrieve with different case section name
  893. self.assertEqual("value1", config[("URL", "https://Example.COM/Path")])
  894. self.assertEqual("value1", config[("url", "https://Example.COM/Path")])
  895. # But not with different case subsection name
  896. with self.assertRaises(KeyError):
  897. config[("url", "https://example.com/path")]
  898. # Verify the stored key preserves subsection case
  899. stored_keys = list(config.keys())
  900. self.assertEqual(1, len(stored_keys))
  901. self.assertEqual(("url", "https://Example.COM/Path"), stored_keys[0])
  902. config[("other",)] = "value3"
  903. self.assertEqual(2, len(config))
  904. def test_make_from_dict(self) -> None:
  905. original = {("core",): "value1", ("other",): "value2"}
  906. config = CaseInsensitiveOrderedMultiDict.make(original)
  907. self.assertEqual("value1", config[("core",)])
  908. self.assertEqual("value1", config[("CORE",)])
  909. self.assertEqual("value2", config[("other",)])
  910. def test_make_from_self(self) -> None:
  911. config1 = CaseInsensitiveOrderedMultiDict()
  912. config1[("core",)] = "value"
  913. config2 = CaseInsensitiveOrderedMultiDict.make(config1)
  914. self.assertIs(config1, config2)
  915. def test_make_invalid_type(self) -> None:
  916. self.assertRaises(TypeError, CaseInsensitiveOrderedMultiDict.make, "invalid")
  917. def test_get_with_default(self) -> None:
  918. config = CaseInsensitiveOrderedMultiDict()
  919. config[("core",)] = "value"
  920. self.assertEqual("value", config.get(("core",)))
  921. self.assertEqual("value", config.get(("CORE",)))
  922. self.assertEqual("default", config.get(("missing",), "default"))
  923. # Test SENTINEL behavior
  924. result = config.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)