test_config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. from io import BytesIO
  25. from unittest import skipIf
  26. from unittest.mock import patch
  27. from dulwich.config import (
  28. ConfigDict,
  29. ConfigFile,
  30. StackedConfig,
  31. _check_section_name,
  32. _check_variable_name,
  33. _escape_value,
  34. _format_string,
  35. _parse_string,
  36. apply_instead_of,
  37. parse_submodules,
  38. )
  39. from . import TestCase
  40. class ConfigFileTests(TestCase):
  41. def from_file(self, text):
  42. return ConfigFile.from_file(BytesIO(text))
  43. def test_empty(self) -> None:
  44. ConfigFile()
  45. def test_eq(self) -> None:
  46. self.assertEqual(ConfigFile(), ConfigFile())
  47. def test_default_config(self) -> None:
  48. cf = self.from_file(
  49. b"""[core]
  50. \trepositoryformatversion = 0
  51. \tfilemode = true
  52. \tbare = false
  53. \tlogallrefupdates = true
  54. """
  55. )
  56. self.assertEqual(
  57. ConfigFile(
  58. {
  59. (b"core",): {
  60. b"repositoryformatversion": b"0",
  61. b"filemode": b"true",
  62. b"bare": b"false",
  63. b"logallrefupdates": b"true",
  64. }
  65. }
  66. ),
  67. cf,
  68. )
  69. def test_from_file_empty(self) -> None:
  70. cf = self.from_file(b"")
  71. self.assertEqual(ConfigFile(), cf)
  72. def test_empty_line_before_section(self) -> None:
  73. cf = self.from_file(b"\n[section]\n")
  74. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  75. def test_comment_before_section(self) -> None:
  76. cf = self.from_file(b"# foo\n[section]\n")
  77. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  78. def test_comment_after_section(self) -> None:
  79. cf = self.from_file(b"[section] # foo\n")
  80. self.assertEqual(ConfigFile({(b"section",): {}}), cf)
  81. def test_comment_after_variable(self) -> None:
  82. cf = self.from_file(b"[section]\nbar= foo # a comment\n")
  83. self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo"}}), cf)
  84. def test_comment_character_within_value_string(self) -> None:
  85. cf = self.from_file(b'[section]\nbar= "foo#bar"\n')
  86. self.assertEqual(ConfigFile({(b"section",): {b"bar": b"foo#bar"}}), cf)
  87. def test_comment_character_within_section_string(self) -> None:
  88. cf = self.from_file(b'[branch "foo#bar"] # a comment\nbar= foo\n')
  89. self.assertEqual(ConfigFile({(b"branch", b"foo#bar"): {b"bar": b"foo"}}), cf)
  90. def test_closing_bracket_within_section_string(self) -> None:
  91. cf = self.from_file(b'[branch "foo]bar"] # a comment\nbar= foo\n')
  92. self.assertEqual(ConfigFile({(b"branch", b"foo]bar"): {b"bar": b"foo"}}), cf)
  93. def test_from_file_section(self) -> None:
  94. cf = self.from_file(b"[core]\nfoo = bar\n")
  95. self.assertEqual(b"bar", cf.get((b"core",), b"foo"))
  96. self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo"))
  97. def test_from_file_multiple(self) -> None:
  98. cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n")
  99. self.assertEqual([b"bar", b"blah"], list(cf.get_multivar((b"core",), b"foo")))
  100. self.assertEqual([], list(cf.get_multivar((b"core",), b"blah")))
  101. def test_from_file_utf8_bom(self) -> None:
  102. text = "[core]\nfoo = b\u00e4r\n".encode("utf-8-sig")
  103. cf = self.from_file(text)
  104. self.assertEqual(b"b\xc3\xa4r", cf.get((b"core",), b"foo"))
  105. def test_from_file_section_case_insensitive_lower(self) -> None:
  106. cf = self.from_file(b"[cOre]\nfOo = bar\n")
  107. self.assertEqual(b"bar", cf.get((b"core",), b"foo"))
  108. self.assertEqual(b"bar", cf.get((b"core", b"foo"), b"foo"))
  109. def test_from_file_section_case_insensitive_mixed(self) -> None:
  110. cf = self.from_file(b"[cOre]\nfOo = bar\n")
  111. self.assertEqual(b"bar", cf.get((b"core",), b"fOo"))
  112. self.assertEqual(b"bar", cf.get((b"cOre", b"fOo"), b"fOo"))
  113. def test_from_file_with_mixed_quoted(self) -> None:
  114. cf = self.from_file(b'[core]\nfoo = "bar"la\n')
  115. self.assertEqual(b"barla", cf.get((b"core",), b"foo"))
  116. def test_from_file_section_with_open_brackets(self) -> None:
  117. self.assertRaises(ValueError, self.from_file, b"[core\nfoo = bar\n")
  118. def test_from_file_value_with_open_quoted(self) -> None:
  119. self.assertRaises(ValueError, self.from_file, b'[core]\nfoo = "bar\n')
  120. def test_from_file_with_quotes(self) -> None:
  121. cf = self.from_file(b"[core]\n" b'foo = " bar"\n')
  122. self.assertEqual(b" bar", cf.get((b"core",), b"foo"))
  123. def test_from_file_with_interrupted_line(self) -> None:
  124. cf = self.from_file(b"[core]\n" b"foo = bar\\\n" b" la\n")
  125. self.assertEqual(b"barla", cf.get((b"core",), b"foo"))
  126. def test_from_file_with_boolean_setting(self) -> None:
  127. cf = self.from_file(b"[core]\n" b"foo\n")
  128. self.assertEqual(b"true", cf.get((b"core",), b"foo"))
  129. def test_from_file_subsection(self) -> None:
  130. cf = self.from_file(b'[branch "foo"]\nfoo = bar\n')
  131. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  132. def test_from_file_subsection_invalid(self) -> None:
  133. self.assertRaises(ValueError, self.from_file, b'[branch "foo]\nfoo = bar\n')
  134. def test_from_file_subsection_not_quoted(self) -> None:
  135. cf = self.from_file(b"[branch.foo]\nfoo = bar\n")
  136. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  137. def test_write_preserve_multivar(self) -> None:
  138. cf = self.from_file(b"[core]\nfoo = bar\nfoo = blah\n")
  139. f = BytesIO()
  140. cf.write_to_file(f)
  141. self.assertEqual(b"[core]\n\tfoo = bar\n\tfoo = blah\n", f.getvalue())
  142. def test_write_to_file_empty(self) -> None:
  143. c = ConfigFile()
  144. f = BytesIO()
  145. c.write_to_file(f)
  146. self.assertEqual(b"", f.getvalue())
  147. def test_write_to_file_section(self) -> None:
  148. c = ConfigFile()
  149. c.set((b"core",), b"foo", b"bar")
  150. f = BytesIO()
  151. c.write_to_file(f)
  152. self.assertEqual(b"[core]\n\tfoo = bar\n", f.getvalue())
  153. def test_write_to_file_subsection(self) -> None:
  154. c = ConfigFile()
  155. c.set((b"branch", b"blie"), b"foo", b"bar")
  156. f = BytesIO()
  157. c.write_to_file(f)
  158. self.assertEqual(b'[branch "blie"]\n\tfoo = bar\n', f.getvalue())
  159. def test_same_line(self) -> None:
  160. cf = self.from_file(b"[branch.foo] foo = bar\n")
  161. self.assertEqual(b"bar", cf.get((b"branch", b"foo"), b"foo"))
  162. def test_quoted_newlines_windows(self) -> None:
  163. cf = self.from_file(
  164. b"[alias]\r\n"
  165. b"c = '!f() { \\\r\n"
  166. b' printf \'[git commit -m \\"%s\\"]\\n\' \\"$*\\" && \\\r\n'
  167. b' git commit -m \\"$*\\"; \\\r\n'
  168. b" }; f'\r\n"
  169. )
  170. self.assertEqual(list(cf.sections()), [(b"alias",)])
  171. self.assertEqual(
  172. b"'!f() { printf '[git commit -m \"%s\"]\n' " b'"$*" && git commit -m "$*"',
  173. cf.get((b"alias",), b"c"),
  174. )
  175. def test_quoted(self) -> None:
  176. cf = self.from_file(
  177. b"""[gui]
  178. \tfontdiff = -family \\\"Ubuntu Mono\\\" -size 11 -overstrike 0
  179. """
  180. )
  181. self.assertEqual(
  182. ConfigFile(
  183. {
  184. (b"gui",): {
  185. b"fontdiff": b'-family "Ubuntu Mono" -size 11 -overstrike 0',
  186. }
  187. }
  188. ),
  189. cf,
  190. )
  191. def test_quoted_multiline(self) -> None:
  192. cf = self.from_file(
  193. b"""[alias]
  194. who = \"!who() {\\
  195. git log --no-merges --pretty=format:'%an - %ae' $@ | uniq -c | sort -rn;\\
  196. };\\
  197. who\"
  198. """
  199. )
  200. self.assertEqual(
  201. ConfigFile(
  202. {
  203. (b"alias",): {
  204. b"who": (
  205. b"!who() {git log --no-merges --pretty=format:'%an - "
  206. b"%ae' $@ | uniq -c | sort -rn;};who"
  207. )
  208. }
  209. }
  210. ),
  211. cf,
  212. )
  213. def test_set_hash_gets_quoted(self) -> None:
  214. c = ConfigFile()
  215. c.set(b"xandikos", b"color", b"#665544")
  216. f = BytesIO()
  217. c.write_to_file(f)
  218. self.assertEqual(b'[xandikos]\n\tcolor = "#665544"\n', f.getvalue())
  219. class ConfigDictTests(TestCase):
  220. def test_get_set(self) -> None:
  221. cd = ConfigDict()
  222. self.assertRaises(KeyError, cd.get, b"foo", b"core")
  223. cd.set((b"core",), b"foo", b"bla")
  224. self.assertEqual(b"bla", cd.get((b"core",), b"foo"))
  225. cd.set((b"core",), b"foo", b"bloe")
  226. self.assertEqual(b"bloe", cd.get((b"core",), b"foo"))
  227. def test_get_boolean(self) -> None:
  228. cd = ConfigDict()
  229. cd.set((b"core",), b"foo", b"true")
  230. self.assertTrue(cd.get_boolean((b"core",), b"foo"))
  231. cd.set((b"core",), b"foo", b"false")
  232. self.assertFalse(cd.get_boolean((b"core",), b"foo"))
  233. cd.set((b"core",), b"foo", b"invalid")
  234. self.assertRaises(ValueError, cd.get_boolean, (b"core",), b"foo")
  235. def test_dict(self) -> None:
  236. cd = ConfigDict()
  237. cd.set((b"core",), b"foo", b"bla")
  238. cd.set((b"core2",), b"foo", b"bloe")
  239. self.assertEqual([(b"core",), (b"core2",)], list(cd.keys()))
  240. self.assertEqual(cd[(b"core",)], {b"foo": b"bla"})
  241. cd[b"a"] = b"b"
  242. self.assertEqual(cd[b"a"], b"b")
  243. def test_items(self) -> None:
  244. cd = ConfigDict()
  245. cd.set((b"core",), b"foo", b"bla")
  246. cd.set((b"core2",), b"foo", b"bloe")
  247. self.assertEqual([(b"foo", b"bla")], list(cd.items((b"core",))))
  248. def test_items_nonexistant(self) -> None:
  249. cd = ConfigDict()
  250. cd.set((b"core2",), b"foo", b"bloe")
  251. self.assertEqual([], list(cd.items((b"core",))))
  252. def test_sections(self) -> None:
  253. cd = ConfigDict()
  254. cd.set((b"core2",), b"foo", b"bloe")
  255. self.assertEqual([(b"core2",)], list(cd.sections()))
  256. class StackedConfigTests(TestCase):
  257. def test_default_backends(self) -> None:
  258. StackedConfig.default_backends()
  259. @skipIf(sys.platform != "win32", "Windows specific config location.")
  260. def test_windows_config_from_path(self) -> None:
  261. from dulwich.config import get_win_system_paths
  262. install_dir = os.path.join("C:", "foo", "Git")
  263. self.overrideEnv("PATH", os.path.join(install_dir, "cmd"))
  264. with patch("os.path.exists", return_value=True):
  265. paths = set(get_win_system_paths())
  266. self.assertEqual(
  267. {
  268. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  269. os.path.join(install_dir, "etc", "gitconfig"),
  270. },
  271. paths,
  272. )
  273. @skipIf(sys.platform != "win32", "Windows specific config location.")
  274. def test_windows_config_from_reg(self) -> None:
  275. import winreg
  276. from dulwich.config import get_win_system_paths
  277. self.overrideEnv("PATH", None)
  278. install_dir = os.path.join("C:", "foo", "Git")
  279. with patch("winreg.OpenKey"):
  280. with patch(
  281. "winreg.QueryValueEx",
  282. return_value=(install_dir, winreg.REG_SZ),
  283. ):
  284. paths = set(get_win_system_paths())
  285. self.assertEqual(
  286. {
  287. os.path.join(os.environ.get("PROGRAMDATA"), "Git", "config"),
  288. os.path.join(install_dir, "etc", "gitconfig"),
  289. },
  290. paths,
  291. )
  292. class EscapeValueTests(TestCase):
  293. def test_nothing(self) -> None:
  294. self.assertEqual(b"foo", _escape_value(b"foo"))
  295. def test_backslash(self) -> None:
  296. self.assertEqual(b"foo\\\\", _escape_value(b"foo\\"))
  297. def test_newline(self) -> None:
  298. self.assertEqual(b"foo\\n", _escape_value(b"foo\n"))
  299. class FormatStringTests(TestCase):
  300. def test_quoted(self) -> None:
  301. self.assertEqual(b'" foo"', _format_string(b" foo"))
  302. self.assertEqual(b'"\\tfoo"', _format_string(b"\tfoo"))
  303. def test_not_quoted(self) -> None:
  304. self.assertEqual(b"foo", _format_string(b"foo"))
  305. self.assertEqual(b"foo bar", _format_string(b"foo bar"))
  306. class ParseStringTests(TestCase):
  307. def test_quoted(self) -> None:
  308. self.assertEqual(b" foo", _parse_string(b'" foo"'))
  309. self.assertEqual(b"\tfoo", _parse_string(b'"\\tfoo"'))
  310. def test_not_quoted(self) -> None:
  311. self.assertEqual(b"foo", _parse_string(b"foo"))
  312. self.assertEqual(b"foo bar", _parse_string(b"foo bar"))
  313. def test_nothing(self) -> None:
  314. self.assertEqual(b"", _parse_string(b""))
  315. def test_tab(self) -> None:
  316. self.assertEqual(b"\tbar\t", _parse_string(b"\\tbar\\t"))
  317. def test_newline(self) -> None:
  318. self.assertEqual(b"\nbar\t", _parse_string(b"\\nbar\\t\t"))
  319. def test_quote(self) -> None:
  320. self.assertEqual(b'"foo"', _parse_string(b'\\"foo\\"'))
  321. class CheckVariableNameTests(TestCase):
  322. def test_invalid(self) -> None:
  323. self.assertFalse(_check_variable_name(b"foo "))
  324. self.assertFalse(_check_variable_name(b"bar,bar"))
  325. self.assertFalse(_check_variable_name(b"bar.bar"))
  326. def test_valid(self) -> None:
  327. self.assertTrue(_check_variable_name(b"FOO"))
  328. self.assertTrue(_check_variable_name(b"foo"))
  329. self.assertTrue(_check_variable_name(b"foo-bar"))
  330. class CheckSectionNameTests(TestCase):
  331. def test_invalid(self) -> None:
  332. self.assertFalse(_check_section_name(b"foo "))
  333. self.assertFalse(_check_section_name(b"bar,bar"))
  334. def test_valid(self) -> None:
  335. self.assertTrue(_check_section_name(b"FOO"))
  336. self.assertTrue(_check_section_name(b"foo"))
  337. self.assertTrue(_check_section_name(b"foo-bar"))
  338. self.assertTrue(_check_section_name(b"bar.bar"))
  339. class SubmodulesTests(TestCase):
  340. def testSubmodules(self) -> None:
  341. cf = ConfigFile.from_file(
  342. BytesIO(
  343. b"""\
  344. [submodule "core/lib"]
  345. \tpath = core/lib
  346. \turl = https://github.com/phhusson/QuasselC.git
  347. """
  348. )
  349. )
  350. got = list(parse_submodules(cf))
  351. self.assertEqual(
  352. [
  353. (
  354. b"core/lib",
  355. b"https://github.com/phhusson/QuasselC.git",
  356. b"core/lib",
  357. )
  358. ],
  359. got,
  360. )
  361. def testMalformedSubmodules(self) -> None:
  362. cf = ConfigFile.from_file(
  363. BytesIO(
  364. b"""\
  365. [submodule "core/lib"]
  366. \tpath = core/lib
  367. \turl = https://github.com/phhusson/QuasselC.git
  368. [submodule "dulwich"]
  369. \turl = https://github.com/jelmer/dulwich
  370. """
  371. )
  372. )
  373. got = list(parse_submodules(cf))
  374. self.assertEqual(
  375. [
  376. (
  377. b"core/lib",
  378. b"https://github.com/phhusson/QuasselC.git",
  379. b"core/lib",
  380. )
  381. ],
  382. got,
  383. )
  384. class ApplyInsteadOfTests(TestCase):
  385. def test_none(self) -> None:
  386. config = ConfigDict()
  387. self.assertEqual(
  388. "https://example.com/", apply_instead_of(config, "https://example.com/")
  389. )
  390. def test_apply(self) -> None:
  391. config = ConfigDict()
  392. config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  393. self.assertEqual(
  394. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  395. )
  396. def test_apply_multiple(self) -> None:
  397. config = ConfigDict()
  398. config.set(("url", "https://samba.org/"), "insteadOf", "https://blah.com/")
  399. config.set(("url", "https://samba.org/"), "insteadOf", "https://example.com/")
  400. self.assertEqual(
  401. [b"https://blah.com/", b"https://example.com/"],
  402. list(config.get_multivar(("url", "https://samba.org/"), "insteadOf")),
  403. )
  404. self.assertEqual(
  405. "https://samba.org/", apply_instead_of(config, "https://example.com/")
  406. )