test_client.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. # test_client.py -- Tests for the git protocol, client side
  2. # Copyright (C) 2009 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. import base64
  22. import os
  23. import shutil
  24. import sys
  25. import tempfile
  26. import warnings
  27. from io import BytesIO
  28. from typing import NoReturn
  29. from unittest.mock import patch
  30. from urllib.parse import quote as urlquote
  31. from urllib.parse import urlparse
  32. import dulwich
  33. from dulwich import client
  34. from dulwich.client import (
  35. FetchPackResult,
  36. GitProtocolError,
  37. HangupException,
  38. HttpGitClient,
  39. InvalidWants,
  40. LocalGitClient,
  41. PLinkSSHVendor,
  42. ReportStatusParser,
  43. SendPackError,
  44. SSHGitClient,
  45. StrangeHostname,
  46. SubprocessSSHVendor,
  47. TCPGitClient,
  48. TraditionalGitClient,
  49. _extract_symrefs_and_agent,
  50. _remote_error_from_stderr,
  51. check_wants,
  52. default_urllib3_manager,
  53. get_credentials_from_store,
  54. get_transport_and_path,
  55. get_transport_and_path_from_url,
  56. parse_rsync_url,
  57. )
  58. from dulwich.config import ConfigDict
  59. from dulwich.objects import Commit, Tree
  60. from dulwich.pack import pack_objects_to_data, write_pack_data, write_pack_objects
  61. from dulwich.protocol import DEFAULT_GIT_PROTOCOL_VERSION_FETCH, TCP_GIT_PORT, Protocol
  62. from dulwich.repo import MemoryRepo, Repo
  63. from dulwich.tests.utils import open_repo, setup_warning_catcher, tear_down_repo
  64. from . import TestCase, skipIf
  65. class DummyClient(TraditionalGitClient):
  66. def __init__(self, can_read, read, write) -> None:
  67. self.can_read = can_read
  68. self.read = read
  69. self.write = write
  70. TraditionalGitClient.__init__(self)
  71. def _connect(self, service, path, protocol_version=None):
  72. return Protocol(self.read, self.write), self.can_read, None
  73. class DummyPopen:
  74. def __init__(self, *args, **kwards) -> None:
  75. self.stdin = BytesIO(b"stdin")
  76. self.stdout = BytesIO(b"stdout")
  77. self.stderr = BytesIO(b"stderr")
  78. self.returncode = 0
  79. self.args = args
  80. self.kwargs = kwards
  81. def communicate(self, *args, **kwards):
  82. return ("Running", "")
  83. def wait(self, *args, **kwards) -> bool:
  84. return False
  85. # TODO(durin42): add unit-level tests of GitClient
  86. class GitClientTests(TestCase):
  87. def setUp(self) -> None:
  88. super().setUp()
  89. self.rout = BytesIO()
  90. self.rin = BytesIO()
  91. self.client = DummyClient(lambda x: True, self.rin.read, self.rout.write)
  92. def test_caps(self) -> None:
  93. agent_cap = ("agent=dulwich/%d.%d.%d" % dulwich.__version__).encode("ascii")
  94. self.assertEqual(
  95. {
  96. b"multi_ack",
  97. b"side-band-64k",
  98. b"ofs-delta",
  99. b"thin-pack",
  100. b"multi_ack_detailed",
  101. b"shallow",
  102. agent_cap,
  103. },
  104. set(self.client._fetch_capabilities),
  105. )
  106. self.assertEqual(
  107. {
  108. b"delete-refs",
  109. b"ofs-delta",
  110. b"report-status",
  111. b"side-band-64k",
  112. agent_cap,
  113. },
  114. set(self.client._send_capabilities),
  115. )
  116. def test_archive_ack(self) -> None:
  117. self.rin.write(b"0009NACK\n" b"0000")
  118. self.rin.seek(0)
  119. self.client.archive(b"bla", b"HEAD", None, None)
  120. self.assertEqual(self.rout.getvalue(), b"0011argument HEAD0000")
  121. def test_fetch_empty(self) -> None:
  122. self.rin.write(b"0000")
  123. self.rin.seek(0)
  124. def check_heads(heads, **kwargs):
  125. self.assertEqual(heads, {})
  126. return []
  127. ret = self.client.fetch_pack(b"/", check_heads, None, None)
  128. self.assertEqual({}, ret.refs)
  129. self.assertEqual({}, ret.symrefs)
  130. def test_fetch_pack_ignores_magic_ref(self) -> None:
  131. self.rin.write(
  132. b"00000000000000000000000000000000000000000000 capabilities^{}"
  133. b"\x00 multi_ack "
  134. b"thin-pack side-band side-band-64k ofs-delta shallow no-progress "
  135. b"include-tag\n"
  136. b"0000"
  137. )
  138. self.rin.seek(0)
  139. def check_heads(heads, **kwargs):
  140. self.assertEqual({}, heads)
  141. return []
  142. ret = self.client.fetch_pack(b"bla", check_heads, None, None, None)
  143. self.assertEqual({}, ret.refs)
  144. self.assertEqual({}, ret.symrefs)
  145. self.assertEqual(self.rout.getvalue(), b"0000")
  146. def test_fetch_pack_none(self) -> None:
  147. self.rin.write(
  148. b"008855dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 HEAD\x00multi_ack "
  149. b"thin-pack side-band side-band-64k ofs-delta shallow no-progress "
  150. b"include-tag\n"
  151. b"0000"
  152. )
  153. self.rin.seek(0)
  154. ret = self.client.fetch_pack(
  155. b"bla", lambda heads, **kwargs: [], None, None, None
  156. )
  157. self.assertEqual(
  158. {b"HEAD": b"55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7"}, ret.refs
  159. )
  160. self.assertEqual({}, ret.symrefs)
  161. self.assertEqual(self.rout.getvalue(), b"0000")
  162. def test_send_pack_no_sideband64k_with_update_ref_error(self) -> None:
  163. # No side-bank-64k reported by server shouldn't try to parse
  164. # side band data
  165. pkts = [
  166. b"55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}"
  167. b"\x00 report-status delete-refs ofs-delta\n",
  168. b"",
  169. b"unpack ok",
  170. b"ng refs/foo/bar pre-receive hook declined",
  171. b"",
  172. ]
  173. for pkt in pkts:
  174. if pkt == b"":
  175. self.rin.write(b"0000")
  176. else:
  177. self.rin.write(("%04x" % (len(pkt) + 4)).encode("ascii") + pkt)
  178. self.rin.seek(0)
  179. tree = Tree()
  180. commit = Commit()
  181. commit.tree = tree
  182. commit.parents = []
  183. commit.author = commit.committer = b"test user"
  184. commit.commit_time = commit.author_time = 1174773719
  185. commit.commit_timezone = commit.author_timezone = 0
  186. commit.encoding = b"UTF-8"
  187. commit.message = b"test message"
  188. def update_refs(refs):
  189. return {
  190. b"refs/foo/bar": commit.id,
  191. }
  192. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  193. return pack_objects_to_data(
  194. [
  195. (commit, None),
  196. (tree, b""),
  197. ]
  198. )
  199. result = self.client.send_pack("blah", update_refs, generate_pack_data)
  200. self.assertEqual(
  201. {b"refs/foo/bar": "pre-receive hook declined"}, result.ref_status
  202. )
  203. self.assertEqual({b"refs/foo/bar": commit.id}, result.refs)
  204. def test_send_pack_none(self) -> None:
  205. # Set ref to current value
  206. self.rin.write(
  207. b"0078310ca9477129b8586fa2afc779c1f57cf64bba6c "
  208. b"refs/heads/master\x00 report-status delete-refs "
  209. b"side-band-64k quiet ofs-delta\n"
  210. b"0000"
  211. )
  212. self.rin.seek(0)
  213. def update_refs(refs):
  214. return {b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c"}
  215. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  216. return 0, []
  217. self.client.send_pack(b"/", update_refs, generate_pack_data)
  218. self.assertEqual(self.rout.getvalue(), b"0000")
  219. def test_send_pack_keep_and_delete(self) -> None:
  220. self.rin.write(
  221. b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c "
  222. b"refs/heads/master\x00report-status delete-refs ofs-delta\n"
  223. b"003f310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/keepme\n"
  224. b"0000000eunpack ok\n"
  225. b"0019ok refs/heads/master\n"
  226. b"0000"
  227. )
  228. self.rin.seek(0)
  229. def update_refs(refs):
  230. return {b"refs/heads/master": b"0" * 40}
  231. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  232. return 0, []
  233. self.client.send_pack(b"/", update_refs, generate_pack_data)
  234. self.assertEqual(
  235. self.rout.getvalue(),
  236. b"008b310ca9477129b8586fa2afc779c1f57cf64bba6c "
  237. b"0000000000000000000000000000000000000000 "
  238. b"refs/heads/master\x00delete-refs ofs-delta report-status0000",
  239. )
  240. def test_send_pack_delete_only(self) -> None:
  241. self.rin.write(
  242. b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c "
  243. b"refs/heads/master\x00report-status delete-refs ofs-delta\n"
  244. b"0000000eunpack ok\n"
  245. b"0019ok refs/heads/master\n"
  246. b"0000"
  247. )
  248. self.rin.seek(0)
  249. def update_refs(refs):
  250. return {b"refs/heads/master": b"0" * 40}
  251. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  252. return 0, []
  253. self.client.send_pack(b"/", update_refs, generate_pack_data)
  254. self.assertEqual(
  255. self.rout.getvalue(),
  256. b"008b310ca9477129b8586fa2afc779c1f57cf64bba6c "
  257. b"0000000000000000000000000000000000000000 "
  258. b"refs/heads/master\x00delete-refs ofs-delta report-status0000",
  259. )
  260. def test_send_pack_new_ref_only(self) -> None:
  261. self.rin.write(
  262. b"0063310ca9477129b8586fa2afc779c1f57cf64bba6c "
  263. b"refs/heads/master\x00report-status delete-refs ofs-delta\n"
  264. b"0000000eunpack ok\n"
  265. b"0019ok refs/heads/blah12\n"
  266. b"0000"
  267. )
  268. self.rin.seek(0)
  269. def update_refs(refs):
  270. return {
  271. b"refs/heads/blah12": b"310ca9477129b8586fa2afc779c1f57cf64bba6c",
  272. b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c",
  273. }
  274. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  275. return 0, []
  276. f = BytesIO()
  277. write_pack_objects(f.write, [])
  278. self.client.send_pack("/", update_refs, generate_pack_data)
  279. self.assertEqual(
  280. self.rout.getvalue(),
  281. b"008b0000000000000000000000000000000000000000 "
  282. b"310ca9477129b8586fa2afc779c1f57cf64bba6c "
  283. b"refs/heads/blah12\x00delete-refs ofs-delta report-status0000"
  284. + f.getvalue(),
  285. )
  286. def test_send_pack_new_ref(self) -> None:
  287. self.rin.write(
  288. b"0064310ca9477129b8586fa2afc779c1f57cf64bba6c "
  289. b"refs/heads/master\x00 report-status delete-refs ofs-delta\n"
  290. b"0000000eunpack ok\n"
  291. b"0019ok refs/heads/blah12\n"
  292. b"0000"
  293. )
  294. self.rin.seek(0)
  295. tree = Tree()
  296. commit = Commit()
  297. commit.tree = tree
  298. commit.parents = []
  299. commit.author = commit.committer = b"test user"
  300. commit.commit_time = commit.author_time = 1174773719
  301. commit.commit_timezone = commit.author_timezone = 0
  302. commit.encoding = b"UTF-8"
  303. commit.message = b"test message"
  304. def update_refs(refs):
  305. return {
  306. b"refs/heads/blah12": commit.id,
  307. b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c",
  308. }
  309. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  310. return pack_objects_to_data(
  311. [
  312. (commit, None),
  313. (tree, b""),
  314. ]
  315. )
  316. f = BytesIO()
  317. count, records = generate_pack_data(None, None)
  318. write_pack_data(f.write, records, num_records=count)
  319. self.client.send_pack(b"/", update_refs, generate_pack_data)
  320. self.assertEqual(
  321. self.rout.getvalue(),
  322. b"008b0000000000000000000000000000000000000000 "
  323. + commit.id
  324. + b" refs/heads/blah12\x00delete-refs ofs-delta report-status0000"
  325. + f.getvalue(),
  326. )
  327. def test_send_pack_no_deleteref_delete_only(self) -> None:
  328. pkts = [
  329. b"310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/master"
  330. b"\x00 report-status ofs-delta\n",
  331. b"",
  332. b"",
  333. ]
  334. for pkt in pkts:
  335. if pkt == b"":
  336. self.rin.write(b"0000")
  337. else:
  338. self.rin.write(("%04x" % (len(pkt) + 4)).encode("ascii") + pkt)
  339. self.rin.seek(0)
  340. def update_refs(refs):
  341. return {b"refs/heads/master": b"0" * 40}
  342. def generate_pack_data(have, want, ofs_delta=False, progress=None):
  343. return 0, []
  344. result = self.client.send_pack(b"/", update_refs, generate_pack_data)
  345. self.assertEqual(
  346. result.ref_status,
  347. {b"refs/heads/master": "remote does not support deleting refs"},
  348. )
  349. self.assertEqual(
  350. result.refs,
  351. {b"refs/heads/master": b"310ca9477129b8586fa2afc779c1f57cf64bba6c"},
  352. )
  353. self.assertEqual(self.rout.getvalue(), b"0000")
  354. class TestGetTransportAndPath(TestCase):
  355. def test_tcp(self) -> None:
  356. c, path = get_transport_and_path("git://foo.com/bar/baz")
  357. self.assertIsInstance(c, TCPGitClient)
  358. self.assertEqual("foo.com", c._host)
  359. self.assertEqual(TCP_GIT_PORT, c._port)
  360. self.assertEqual("/bar/baz", path)
  361. def test_tcp_port(self) -> None:
  362. c, path = get_transport_and_path("git://foo.com:1234/bar/baz")
  363. self.assertIsInstance(c, TCPGitClient)
  364. self.assertEqual("foo.com", c._host)
  365. self.assertEqual(1234, c._port)
  366. self.assertEqual("/bar/baz", path)
  367. def test_git_ssh_explicit(self) -> None:
  368. c, path = get_transport_and_path("git+ssh://foo.com/bar/baz")
  369. self.assertIsInstance(c, SSHGitClient)
  370. self.assertEqual("foo.com", c.host)
  371. self.assertEqual(None, c.port)
  372. self.assertEqual(None, c.username)
  373. self.assertEqual("/bar/baz", path)
  374. def test_ssh_explicit(self) -> None:
  375. c, path = get_transport_and_path("ssh://foo.com/bar/baz")
  376. self.assertIsInstance(c, SSHGitClient)
  377. self.assertEqual("foo.com", c.host)
  378. self.assertEqual(None, c.port)
  379. self.assertEqual(None, c.username)
  380. self.assertEqual("/bar/baz", path)
  381. def test_ssh_port_explicit(self) -> None:
  382. c, path = get_transport_and_path("git+ssh://foo.com:1234/bar/baz")
  383. self.assertIsInstance(c, SSHGitClient)
  384. self.assertEqual("foo.com", c.host)
  385. self.assertEqual(1234, c.port)
  386. self.assertEqual("/bar/baz", path)
  387. def test_username_and_port_explicit_unknown_scheme(self) -> None:
  388. c, path = get_transport_and_path("unknown://git@server:7999/dply/stuff.git")
  389. self.assertIsInstance(c, SSHGitClient)
  390. self.assertEqual("unknown", c.host)
  391. self.assertEqual("//git@server:7999/dply/stuff.git", path)
  392. def test_username_and_port_explicit(self) -> None:
  393. c, path = get_transport_and_path("ssh://git@server:7999/dply/stuff.git")
  394. self.assertIsInstance(c, SSHGitClient)
  395. self.assertEqual("git", c.username)
  396. self.assertEqual("server", c.host)
  397. self.assertEqual(7999, c.port)
  398. self.assertEqual("/dply/stuff.git", path)
  399. def test_ssh_abspath_doubleslash(self) -> None:
  400. c, path = get_transport_and_path("git+ssh://foo.com//bar/baz")
  401. self.assertIsInstance(c, SSHGitClient)
  402. self.assertEqual("foo.com", c.host)
  403. self.assertEqual(None, c.port)
  404. self.assertEqual(None, c.username)
  405. self.assertEqual("//bar/baz", path)
  406. def test_ssh_port(self) -> None:
  407. c, path = get_transport_and_path("git+ssh://foo.com:1234/bar/baz")
  408. self.assertIsInstance(c, SSHGitClient)
  409. self.assertEqual("foo.com", c.host)
  410. self.assertEqual(1234, c.port)
  411. self.assertEqual("/bar/baz", path)
  412. def test_ssh_implicit(self) -> None:
  413. c, path = get_transport_and_path("foo:/bar/baz")
  414. self.assertIsInstance(c, SSHGitClient)
  415. self.assertEqual("foo", c.host)
  416. self.assertEqual(None, c.port)
  417. self.assertEqual(None, c.username)
  418. self.assertEqual("/bar/baz", path)
  419. def test_ssh_host(self) -> None:
  420. c, path = get_transport_and_path("foo.com:/bar/baz")
  421. self.assertIsInstance(c, SSHGitClient)
  422. self.assertEqual("foo.com", c.host)
  423. self.assertEqual(None, c.port)
  424. self.assertEqual(None, c.username)
  425. self.assertEqual("/bar/baz", path)
  426. def test_ssh_user_host(self) -> None:
  427. c, path = get_transport_and_path("user@foo.com:/bar/baz")
  428. self.assertIsInstance(c, SSHGitClient)
  429. self.assertEqual("foo.com", c.host)
  430. self.assertEqual(None, c.port)
  431. self.assertEqual("user", c.username)
  432. self.assertEqual("/bar/baz", path)
  433. def test_ssh_relpath(self) -> None:
  434. c, path = get_transport_and_path("foo:bar/baz")
  435. self.assertIsInstance(c, SSHGitClient)
  436. self.assertEqual("foo", c.host)
  437. self.assertEqual(None, c.port)
  438. self.assertEqual(None, c.username)
  439. self.assertEqual("bar/baz", path)
  440. def test_ssh_host_relpath(self) -> None:
  441. c, path = get_transport_and_path("foo.com:bar/baz")
  442. self.assertIsInstance(c, SSHGitClient)
  443. self.assertEqual("foo.com", c.host)
  444. self.assertEqual(None, c.port)
  445. self.assertEqual(None, c.username)
  446. self.assertEqual("bar/baz", path)
  447. def test_ssh_user_host_relpath(self) -> None:
  448. c, path = get_transport_and_path("user@foo.com:bar/baz")
  449. self.assertIsInstance(c, SSHGitClient)
  450. self.assertEqual("foo.com", c.host)
  451. self.assertEqual(None, c.port)
  452. self.assertEqual("user", c.username)
  453. self.assertEqual("bar/baz", path)
  454. def test_local(self) -> None:
  455. c, path = get_transport_and_path("foo.bar/baz")
  456. self.assertIsInstance(c, LocalGitClient)
  457. self.assertEqual("foo.bar/baz", path)
  458. @skipIf(sys.platform != "win32", "Behaviour only happens on windows.")
  459. def test_local_abs_windows_path(self) -> None:
  460. c, path = get_transport_and_path("C:\\foo.bar\\baz")
  461. self.assertIsInstance(c, LocalGitClient)
  462. self.assertEqual("C:\\foo.bar\\baz", path)
  463. def test_error(self) -> None:
  464. # Need to use a known urlparse.uses_netloc URL scheme to get the
  465. # expected parsing of the URL on Python versions less than 2.6.5
  466. c, path = get_transport_and_path("prospero://bar/baz")
  467. self.assertIsInstance(c, SSHGitClient)
  468. def test_http(self) -> None:
  469. url = "https://github.com/jelmer/dulwich"
  470. c, path = get_transport_and_path(url)
  471. self.assertIsInstance(c, HttpGitClient)
  472. self.assertEqual("/jelmer/dulwich", path)
  473. def test_http_auth(self) -> None:
  474. url = "https://user:passwd@github.com/jelmer/dulwich"
  475. c, path = get_transport_and_path(url)
  476. self.assertIsInstance(c, HttpGitClient)
  477. self.assertEqual("/jelmer/dulwich", path)
  478. self.assertEqual("user", c._username)
  479. self.assertEqual("passwd", c._password)
  480. def test_http_auth_with_username(self) -> None:
  481. url = "https://github.com/jelmer/dulwich"
  482. c, path = get_transport_and_path(url, username="user2", password="blah")
  483. self.assertIsInstance(c, HttpGitClient)
  484. self.assertEqual("/jelmer/dulwich", path)
  485. self.assertEqual("user2", c._username)
  486. self.assertEqual("blah", c._password)
  487. def test_http_auth_with_username_and_in_url(self) -> None:
  488. url = "https://user:passwd@github.com/jelmer/dulwich"
  489. c, path = get_transport_and_path(url, username="user2", password="blah")
  490. self.assertIsInstance(c, HttpGitClient)
  491. self.assertEqual("/jelmer/dulwich", path)
  492. self.assertEqual("user", c._username)
  493. self.assertEqual("passwd", c._password)
  494. def test_http_no_auth(self) -> None:
  495. url = "https://github.com/jelmer/dulwich"
  496. c, path = get_transport_and_path(url)
  497. self.assertIsInstance(c, HttpGitClient)
  498. self.assertEqual("/jelmer/dulwich", path)
  499. self.assertIs(None, c._username)
  500. self.assertIs(None, c._password)
  501. class TestGetTransportAndPathFromUrl(TestCase):
  502. def test_tcp(self) -> None:
  503. c, path = get_transport_and_path_from_url("git://foo.com/bar/baz")
  504. self.assertIsInstance(c, TCPGitClient)
  505. self.assertEqual("foo.com", c._host)
  506. self.assertEqual(TCP_GIT_PORT, c._port)
  507. self.assertEqual("/bar/baz", path)
  508. def test_tcp_port(self) -> None:
  509. c, path = get_transport_and_path_from_url("git://foo.com:1234/bar/baz")
  510. self.assertIsInstance(c, TCPGitClient)
  511. self.assertEqual("foo.com", c._host)
  512. self.assertEqual(1234, c._port)
  513. self.assertEqual("/bar/baz", path)
  514. def test_ssh_explicit(self) -> None:
  515. c, path = get_transport_and_path_from_url("git+ssh://foo.com/bar/baz")
  516. self.assertIsInstance(c, SSHGitClient)
  517. self.assertEqual("foo.com", c.host)
  518. self.assertEqual(None, c.port)
  519. self.assertEqual(None, c.username)
  520. self.assertEqual("/bar/baz", path)
  521. def test_ssh_port_explicit(self) -> None:
  522. c, path = get_transport_and_path_from_url("git+ssh://foo.com:1234/bar/baz")
  523. self.assertIsInstance(c, SSHGitClient)
  524. self.assertEqual("foo.com", c.host)
  525. self.assertEqual(1234, c.port)
  526. self.assertEqual("/bar/baz", path)
  527. def test_ssh_homepath(self) -> None:
  528. c, path = get_transport_and_path_from_url("git+ssh://foo.com/~/bar/baz")
  529. self.assertIsInstance(c, SSHGitClient)
  530. self.assertEqual("foo.com", c.host)
  531. self.assertEqual(None, c.port)
  532. self.assertEqual(None, c.username)
  533. self.assertEqual("/~/bar/baz", path)
  534. def test_ssh_port_homepath(self) -> None:
  535. c, path = get_transport_and_path_from_url("git+ssh://foo.com:1234/~/bar/baz")
  536. self.assertIsInstance(c, SSHGitClient)
  537. self.assertEqual("foo.com", c.host)
  538. self.assertEqual(1234, c.port)
  539. self.assertEqual("/~/bar/baz", path)
  540. def test_ssh_host_relpath(self) -> None:
  541. self.assertRaises(
  542. ValueError, get_transport_and_path_from_url, "foo.com:bar/baz"
  543. )
  544. def test_ssh_user_host_relpath(self) -> None:
  545. self.assertRaises(
  546. ValueError, get_transport_and_path_from_url, "user@foo.com:bar/baz"
  547. )
  548. def test_local_path(self) -> None:
  549. self.assertRaises(ValueError, get_transport_and_path_from_url, "foo.bar/baz")
  550. def test_error(self) -> None:
  551. # Need to use a known urlparse.uses_netloc URL scheme to get the
  552. # expected parsing of the URL on Python versions less than 2.6.5
  553. self.assertRaises(
  554. ValueError, get_transport_and_path_from_url, "prospero://bar/baz"
  555. )
  556. def test_http(self) -> None:
  557. url = "https://github.com/jelmer/dulwich"
  558. c, path = get_transport_and_path_from_url(url)
  559. self.assertIsInstance(c, HttpGitClient)
  560. self.assertEqual("https://github.com", c.get_url(b"/"))
  561. self.assertEqual("/jelmer/dulwich", path)
  562. def test_http_port(self) -> None:
  563. url = "https://github.com:9090/jelmer/dulwich"
  564. c, path = get_transport_and_path_from_url(url)
  565. self.assertEqual("https://github.com:9090", c.get_url(b"/"))
  566. self.assertIsInstance(c, HttpGitClient)
  567. self.assertEqual("/jelmer/dulwich", path)
  568. @patch("os.name", "posix")
  569. @patch("sys.platform", "linux")
  570. def test_file(self) -> None:
  571. c, path = get_transport_and_path_from_url("file:///home/jelmer/foo")
  572. self.assertIsInstance(c, LocalGitClient)
  573. self.assertEqual("/home/jelmer/foo", path)
  574. @patch("os.name", "nt")
  575. @patch("sys.platform", "win32")
  576. def test_file_win(self) -> None:
  577. # `_win32_url_to_path` uses urllib.request.url2pathname, which is set to
  578. # `ntutl2path.url2pathname` when `os.name==nt`
  579. from nturl2path import url2pathname
  580. with patch("dulwich.client.url2pathname", url2pathname):
  581. expected = "C:\\foo.bar\\baz"
  582. for file_url in [
  583. "file:C:/foo.bar/baz",
  584. "file:/C:/foo.bar/baz",
  585. "file://C:/foo.bar/baz",
  586. "file://C://foo.bar//baz",
  587. "file:///C:/foo.bar/baz",
  588. ]:
  589. c, path = get_transport_and_path(file_url)
  590. self.assertIsInstance(c, LocalGitClient)
  591. self.assertEqual(path, expected)
  592. for remote_url in [
  593. "file://host.example.com/C:/foo.bar/baz"
  594. "file://host.example.com/C:/foo.bar/baz"
  595. "file:////host.example/foo.bar/baz",
  596. ]:
  597. with self.assertRaises(NotImplementedError):
  598. c, path = get_transport_and_path(remote_url)
  599. class TestSSHVendor:
  600. def __init__(self) -> None:
  601. self.host = None
  602. self.command = ""
  603. self.username = None
  604. self.port = None
  605. self.password = None
  606. self.key_filename = None
  607. def run_command(
  608. self,
  609. host,
  610. command,
  611. username=None,
  612. port=None,
  613. password=None,
  614. key_filename=None,
  615. ssh_command=None,
  616. protocol_version=None,
  617. ):
  618. self.host = host
  619. self.command = command
  620. self.username = username
  621. self.port = port
  622. self.password = password
  623. self.key_filename = key_filename
  624. self.ssh_command = ssh_command
  625. self.protocol_version = protocol_version
  626. class Subprocess:
  627. pass
  628. Subprocess.read = lambda: None
  629. Subprocess.write = lambda: None
  630. Subprocess.close = lambda: None
  631. Subprocess.can_read = lambda: None
  632. return Subprocess()
  633. class SSHGitClientTests(TestCase):
  634. def setUp(self) -> None:
  635. super().setUp()
  636. self.server = TestSSHVendor()
  637. self.real_vendor = client.get_ssh_vendor
  638. client.get_ssh_vendor = lambda: self.server
  639. self.client = SSHGitClient("git.samba.org")
  640. def tearDown(self) -> None:
  641. super().tearDown()
  642. client.get_ssh_vendor = self.real_vendor
  643. def test_get_url(self) -> None:
  644. path = "/tmp/repo.git"
  645. c = SSHGitClient("git.samba.org")
  646. url = c.get_url(path)
  647. self.assertEqual("ssh://git.samba.org/tmp/repo.git", url)
  648. def test_get_url_with_username_and_port(self) -> None:
  649. path = "/tmp/repo.git"
  650. c = SSHGitClient("git.samba.org", port=2222, username="user")
  651. url = c.get_url(path)
  652. self.assertEqual("ssh://user@git.samba.org:2222/tmp/repo.git", url)
  653. def test_default_command(self) -> None:
  654. self.assertEqual(b"git-upload-pack", self.client._get_cmd_path(b"upload-pack"))
  655. def test_alternative_command_path(self) -> None:
  656. self.client.alternative_paths[b"upload-pack"] = b"/usr/lib/git/git-upload-pack"
  657. self.assertEqual(
  658. b"/usr/lib/git/git-upload-pack",
  659. self.client._get_cmd_path(b"upload-pack"),
  660. )
  661. def test_alternative_command_path_spaces(self) -> None:
  662. self.client.alternative_paths[b"upload-pack"] = (
  663. b"/usr/lib/git/git-upload-pack -ibla"
  664. )
  665. self.assertEqual(
  666. b"/usr/lib/git/git-upload-pack -ibla",
  667. self.client._get_cmd_path(b"upload-pack"),
  668. )
  669. def test_connect(self) -> None:
  670. server = self.server
  671. client = self.client
  672. client.username = b"username"
  673. client.port = 1337
  674. client._connect(b"command", b"/path/to/repo")
  675. self.assertEqual(b"username", server.username)
  676. self.assertEqual(1337, server.port)
  677. self.assertEqual("git-command '/path/to/repo'", server.command)
  678. client._connect(b"relative-command", b"/~/path/to/repo")
  679. self.assertEqual("git-relative-command '~/path/to/repo'", server.command)
  680. def test_ssh_command_precedence(self) -> None:
  681. self.overrideEnv("GIT_SSH", "/path/to/ssh")
  682. test_client = SSHGitClient("git.samba.org")
  683. self.assertEqual(test_client.ssh_command, "/path/to/ssh")
  684. self.overrideEnv("GIT_SSH_COMMAND", "/path/to/ssh -o Option=Value")
  685. test_client = SSHGitClient("git.samba.org")
  686. self.assertEqual(test_client.ssh_command, "/path/to/ssh -o Option=Value")
  687. test_client = SSHGitClient("git.samba.org", ssh_command="ssh -o Option1=Value1")
  688. self.assertEqual(test_client.ssh_command, "ssh -o Option1=Value1")
  689. class ReportStatusParserTests(TestCase):
  690. def test_invalid_pack(self) -> None:
  691. parser = ReportStatusParser()
  692. parser.handle_packet(b"unpack error - foo bar")
  693. parser.handle_packet(b"ok refs/foo/bar")
  694. parser.handle_packet(None)
  695. self.assertRaises(SendPackError, list, parser.check())
  696. def test_update_refs_error(self) -> None:
  697. parser = ReportStatusParser()
  698. parser.handle_packet(b"unpack ok")
  699. parser.handle_packet(b"ng refs/foo/bar need to pull")
  700. parser.handle_packet(None)
  701. self.assertEqual([(b"refs/foo/bar", "need to pull")], list(parser.check()))
  702. def test_ok(self) -> None:
  703. parser = ReportStatusParser()
  704. parser.handle_packet(b"unpack ok")
  705. parser.handle_packet(b"ok refs/foo/bar")
  706. parser.handle_packet(None)
  707. self.assertEqual([(b"refs/foo/bar", None)], list(parser.check()))
  708. class LocalGitClientTests(TestCase):
  709. def test_get_url(self) -> None:
  710. path = "/tmp/repo.git"
  711. c = LocalGitClient()
  712. url = c.get_url(path)
  713. self.assertEqual("file:///tmp/repo.git", url)
  714. def test_fetch_into_empty(self) -> None:
  715. c = LocalGitClient()
  716. target = tempfile.mkdtemp()
  717. self.addCleanup(shutil.rmtree, target)
  718. t = Repo.init_bare(target)
  719. self.addCleanup(t.close)
  720. s = open_repo("a.git")
  721. self.addCleanup(tear_down_repo, s)
  722. self.assertEqual(s.get_refs(), c.fetch(s.path, t).refs)
  723. def test_clone(self) -> None:
  724. c = LocalGitClient()
  725. s = open_repo("a.git")
  726. self.addCleanup(tear_down_repo, s)
  727. target = tempfile.mkdtemp()
  728. self.addCleanup(shutil.rmtree, target)
  729. result_repo = c.clone(s.path, target, mkdir=False)
  730. self.addCleanup(result_repo.close)
  731. expected = dict(s.get_refs())
  732. expected[b"refs/remotes/origin/HEAD"] = expected[b"HEAD"]
  733. expected[b"refs/remotes/origin/master"] = expected[b"refs/heads/master"]
  734. self.assertEqual(expected, result_repo.get_refs())
  735. def test_fetch_empty(self) -> None:
  736. c = LocalGitClient()
  737. s = open_repo("a.git")
  738. self.addCleanup(tear_down_repo, s)
  739. out = BytesIO()
  740. walker = {}
  741. ret = c.fetch_pack(
  742. s.path, lambda heads, **kwargs: [], graph_walker=walker, pack_data=out.write
  743. )
  744. self.assertEqual(
  745. {
  746. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  747. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  748. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  749. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  750. },
  751. ret.refs,
  752. )
  753. self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs)
  754. self.assertEqual(
  755. b"PACK\x00\x00\x00\x02\x00\x00\x00\x00\x02\x9d\x08"
  756. b"\x82;\xd8\xa8\xea\xb5\x10\xadj\xc7\\\x82<\xfd>\xd3\x1e",
  757. out.getvalue(),
  758. )
  759. def test_fetch_pack_none(self) -> None:
  760. c = LocalGitClient()
  761. s = open_repo("a.git")
  762. self.addCleanup(tear_down_repo, s)
  763. out = BytesIO()
  764. walker = MemoryRepo().get_graph_walker()
  765. ret = c.fetch_pack(
  766. s.path,
  767. lambda heads, **kwargs: [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  768. graph_walker=walker,
  769. pack_data=out.write,
  770. )
  771. self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs)
  772. self.assertEqual(
  773. {
  774. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  775. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  776. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  777. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  778. },
  779. ret.refs,
  780. )
  781. # Hardcoding is not ideal, but we'll fix that some other day..
  782. self.assertTrue(
  783. out.getvalue().startswith(b"PACK\x00\x00\x00\x02\x00\x00\x00\x07")
  784. )
  785. def test_send_pack_without_changes(self) -> None:
  786. local = open_repo("a.git")
  787. self.addCleanup(tear_down_repo, local)
  788. target = open_repo("a.git")
  789. self.addCleanup(tear_down_repo, target)
  790. self.send_and_verify(b"master", local, target)
  791. def test_send_pack_with_changes(self) -> None:
  792. local = open_repo("a.git")
  793. self.addCleanup(tear_down_repo, local)
  794. target_path = tempfile.mkdtemp()
  795. self.addCleanup(shutil.rmtree, target_path)
  796. with Repo.init_bare(target_path) as target:
  797. self.send_and_verify(b"master", local, target)
  798. def test_get_refs(self) -> None:
  799. local = open_repo("refs.git")
  800. self.addCleanup(tear_down_repo, local)
  801. client = LocalGitClient()
  802. refs = client.get_refs(local.path)
  803. self.assertDictEqual(local.refs.as_dict(), refs)
  804. def send_and_verify(self, branch, local, target) -> None:
  805. """Send branch from local to remote repository and verify it worked."""
  806. client = LocalGitClient()
  807. ref_name = b"refs/heads/" + branch
  808. result = client.send_pack(
  809. target.path,
  810. lambda _: {ref_name: local.refs[ref_name]},
  811. local.generate_pack_data,
  812. )
  813. self.assertEqual(local.refs[ref_name], result.refs[ref_name])
  814. self.assertIs(None, result.agent)
  815. self.assertEqual({}, result.ref_status)
  816. obj_local = local.get_object(result.refs[ref_name])
  817. obj_target = target.get_object(result.refs[ref_name])
  818. self.assertEqual(obj_local, obj_target)
  819. class HttpGitClientTests(TestCase):
  820. def test_get_url(self) -> None:
  821. base_url = "https://github.com/jelmer/dulwich"
  822. path = "/jelmer/dulwich"
  823. c = HttpGitClient(base_url)
  824. url = c.get_url(path)
  825. self.assertEqual("https://github.com/jelmer/dulwich", url)
  826. def test_get_url_bytes_path(self) -> None:
  827. base_url = "https://github.com/jelmer/dulwich"
  828. path_bytes = b"/jelmer/dulwich"
  829. c = HttpGitClient(base_url)
  830. url = c.get_url(path_bytes)
  831. self.assertEqual("https://github.com/jelmer/dulwich", url)
  832. def test_get_url_with_username_and_passwd(self) -> None:
  833. base_url = "https://github.com/jelmer/dulwich"
  834. path = "/jelmer/dulwich"
  835. c = HttpGitClient(base_url, username="USERNAME", password="PASSWD")
  836. url = c.get_url(path)
  837. self.assertEqual("https://github.com/jelmer/dulwich", url)
  838. def test_init_username_passwd_set(self) -> None:
  839. url = "https://github.com/jelmer/dulwich"
  840. c = HttpGitClient(url, config=None, username="user", password="passwd")
  841. self.assertEqual("user", c._username)
  842. self.assertEqual("passwd", c._password)
  843. basic_auth = c.pool_manager.headers["authorization"]
  844. auth_string = "{}:{}".format("user", "passwd")
  845. b64_credentials = base64.b64encode(auth_string.encode("latin1"))
  846. expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1"))
  847. self.assertEqual(basic_auth, expected_basic_auth)
  848. def test_init_username_set_no_password(self) -> None:
  849. url = "https://github.com/jelmer/dulwich"
  850. c = HttpGitClient(url, config=None, username="user")
  851. self.assertEqual("user", c._username)
  852. self.assertIsNone(c._password)
  853. basic_auth = c.pool_manager.headers["authorization"]
  854. auth_string = b"user:"
  855. b64_credentials = base64.b64encode(auth_string)
  856. expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}"
  857. self.assertEqual(basic_auth, expected_basic_auth)
  858. def test_init_no_username_passwd(self) -> None:
  859. url = "https://github.com/jelmer/dulwich"
  860. c = HttpGitClient(url, config=None)
  861. self.assertIs(None, c._username)
  862. self.assertIs(None, c._password)
  863. self.assertNotIn("authorization", c.pool_manager.headers)
  864. def test_from_parsedurl_username_only(self) -> None:
  865. username = "user"
  866. url = f"https://{username}@github.com/jelmer/dulwich"
  867. c = HttpGitClient.from_parsedurl(urlparse(url))
  868. self.assertEqual(c._username, username)
  869. self.assertEqual(c._password, None)
  870. basic_auth = c.pool_manager.headers["authorization"]
  871. auth_string = username.encode("ascii") + b":"
  872. b64_credentials = base64.b64encode(auth_string)
  873. expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}"
  874. self.assertEqual(basic_auth, expected_basic_auth)
  875. def test_from_parsedurl_on_url_with_quoted_credentials(self) -> None:
  876. original_username = "john|the|first"
  877. quoted_username = urlquote(original_username)
  878. original_password = "Ya#1$2%3"
  879. quoted_password = urlquote(original_password)
  880. url = f"https://{quoted_username}:{quoted_password}@github.com/jelmer/dulwich"
  881. c = HttpGitClient.from_parsedurl(urlparse(url))
  882. self.assertEqual(original_username, c._username)
  883. self.assertEqual(original_password, c._password)
  884. basic_auth = c.pool_manager.headers["authorization"]
  885. auth_string = f"{original_username}:{original_password}"
  886. b64_credentials = base64.b64encode(auth_string.encode("latin1"))
  887. expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1"))
  888. self.assertEqual(basic_auth, expected_basic_auth)
  889. def test_url_redirect_location(self) -> None:
  890. from urllib3.response import HTTPResponse
  891. test_data = {
  892. "https://gitlab.com/inkscape/inkscape/": {
  893. "location": "https://gitlab.com/inkscape/inkscape.git/",
  894. "redirect_url": "https://gitlab.com/inkscape/inkscape.git/",
  895. "refs_data": (
  896. b"001e# service=git-upload-pack\n00000032"
  897. b"fb2bebf4919a011f0fd7cec085443d0031228e76 "
  898. b"HEAD\n0000"
  899. ),
  900. },
  901. "https://github.com/jelmer/dulwich/": {
  902. "location": "https://github.com/jelmer/dulwich/",
  903. "redirect_url": "https://github.com/jelmer/dulwich/",
  904. "refs_data": (
  905. b"001e# service=git-upload-pack\n00000032"
  906. b"3ff25e09724aa4d86ea5bca7d5dd0399a3c8bfcf "
  907. b"HEAD\n0000"
  908. ),
  909. },
  910. # check for absolute-path URI reference as location
  911. "https://codeberg.org/ashwinvis/radicale-sh.git/": {
  912. "location": "/ashwinvis/radicale-auth-sh/",
  913. "redirect_url": "https://codeberg.org/ashwinvis/radicale-auth-sh/",
  914. "refs_data": (
  915. b"001e# service=git-upload-pack\n00000032"
  916. b"470f8603768b608fc988675de2fae8f963c21158 "
  917. b"HEAD\n0000"
  918. ),
  919. },
  920. }
  921. tail = "info/refs?service=git-upload-pack"
  922. # we need to mock urllib3.PoolManager as this test will fail
  923. # otherwise without an active internet connection
  924. class PoolManagerMock:
  925. def __init__(self) -> None:
  926. self.headers: dict[str, str] = {}
  927. def request(
  928. self,
  929. method,
  930. url,
  931. fields=None,
  932. headers=None,
  933. redirect=True,
  934. preload_content=True,
  935. ):
  936. base_url = url[: -len(tail)]
  937. redirect_base_url = test_data[base_url]["location"]
  938. redirect_url = redirect_base_url + tail
  939. headers = {
  940. "Content-Type": "application/x-git-upload-pack-advertisement"
  941. }
  942. body = test_data[base_url]["refs_data"]
  943. # urllib3 handles automatic redirection by default
  944. status = 200
  945. request_url = redirect_url
  946. # simulate urllib3 behavior when redirect parameter is False
  947. if redirect is False:
  948. request_url = url
  949. if redirect_base_url != base_url:
  950. body = b""
  951. headers["location"] = test_data[base_url]["location"]
  952. status = 301
  953. return HTTPResponse(
  954. body=BytesIO(body),
  955. headers=headers,
  956. request_method=method,
  957. request_url=request_url,
  958. preload_content=preload_content,
  959. status=status,
  960. )
  961. pool_manager = PoolManagerMock()
  962. for base_url in test_data.keys():
  963. # instantiate HttpGitClient with mocked pool manager
  964. c = HttpGitClient(base_url, pool_manager=pool_manager, config=None)
  965. # call method that detects url redirection
  966. _, _, processed_url, _, _ = c._discover_references(
  967. b"git-upload-pack", base_url
  968. )
  969. # send the same request as the method above without redirection
  970. resp = c.pool_manager.request("GET", base_url + tail, redirect=False)
  971. # check expected behavior of urllib3
  972. redirect_location = resp.get_redirect_location()
  973. if resp.status == 200:
  974. self.assertFalse(redirect_location)
  975. if redirect_location:
  976. # check that url redirection has been correctly detected
  977. self.assertEqual(processed_url, test_data[base_url]["redirect_url"])
  978. else:
  979. # check also the no redirection case
  980. self.assertEqual(processed_url, base_url)
  981. def test_smart_request_content_type_with_directive_check(self) -> None:
  982. from urllib3.response import HTTPResponse
  983. # we need to mock urllib3.PoolManager as this test will fail
  984. # otherwise without an active internet connection
  985. class PoolManagerMock:
  986. def __init__(self) -> None:
  987. self.headers: dict[str, str] = {}
  988. def request(
  989. self,
  990. method,
  991. url,
  992. fields=None,
  993. headers=None,
  994. redirect=True,
  995. preload_content=True,
  996. ):
  997. return HTTPResponse(
  998. headers={
  999. "Content-Type": "application/x-git-upload-pack-result; charset=utf-8"
  1000. },
  1001. request_method=method,
  1002. request_url=url,
  1003. preload_content=preload_content,
  1004. status=200,
  1005. )
  1006. clone_url = "https://hacktivis.me/git/blog.git/"
  1007. client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None)
  1008. self.assertTrue(client._smart_request("git-upload-pack", clone_url, data=None))
  1009. def test_urllib3_protocol_error(self) -> None:
  1010. from urllib3.exceptions import ProtocolError
  1011. from urllib3.response import HTTPResponse
  1012. error_msg = "protocol error"
  1013. # we need to mock urllib3.PoolManager as this test will fail
  1014. # otherwise without an active internet connection
  1015. class PoolManagerMock:
  1016. def __init__(self) -> None:
  1017. self.headers: dict[str, str] = {}
  1018. def request(
  1019. self,
  1020. method,
  1021. url,
  1022. fields=None,
  1023. headers=None,
  1024. redirect=True,
  1025. preload_content=True,
  1026. ):
  1027. response = HTTPResponse(
  1028. headers={"Content-Type": "application/x-git-upload-pack-result"},
  1029. request_method=method,
  1030. request_url=url,
  1031. preload_content=preload_content,
  1032. status=200,
  1033. )
  1034. def read(self) -> NoReturn:
  1035. raise ProtocolError(error_msg)
  1036. # override HTTPResponse.read to throw urllib3.exceptions.ProtocolError
  1037. response.read = read
  1038. return response
  1039. def check_heads(heads, **kwargs):
  1040. self.assertEqual(heads, {})
  1041. return []
  1042. clone_url = "https://git.example.org/user/project.git/"
  1043. client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None)
  1044. with self.assertRaises(GitProtocolError, msg=error_msg):
  1045. client.fetch_pack(b"/", check_heads, None, None)
  1046. class TCPGitClientTests(TestCase):
  1047. def test_get_url(self) -> None:
  1048. host = "github.com"
  1049. path = "/jelmer/dulwich"
  1050. c = TCPGitClient(host)
  1051. url = c.get_url(path)
  1052. self.assertEqual("git://github.com/jelmer/dulwich", url)
  1053. def test_get_url_with_port(self) -> None:
  1054. host = "github.com"
  1055. path = "/jelmer/dulwich"
  1056. port = 9090
  1057. c = TCPGitClient(host, port=port)
  1058. url = c.get_url(path)
  1059. self.assertEqual("git://github.com:9090/jelmer/dulwich", url)
  1060. class DefaultUrllib3ManagerTest(TestCase):
  1061. def test_no_config(self) -> None:
  1062. manager = default_urllib3_manager(config=None)
  1063. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED")
  1064. def test_config_no_proxy(self) -> None:
  1065. import urllib3
  1066. manager = default_urllib3_manager(config=ConfigDict())
  1067. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1068. self.assertIsInstance(manager, urllib3.PoolManager)
  1069. def test_config_no_proxy_custom_cls(self) -> None:
  1070. import urllib3
  1071. class CustomPoolManager(urllib3.PoolManager):
  1072. pass
  1073. manager = default_urllib3_manager(
  1074. config=ConfigDict(), pool_manager_cls=CustomPoolManager
  1075. )
  1076. self.assertIsInstance(manager, CustomPoolManager)
  1077. def test_config_ssl(self) -> None:
  1078. config = ConfigDict()
  1079. config.set(b"http", b"sslVerify", b"true")
  1080. manager = default_urllib3_manager(config=config)
  1081. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED")
  1082. def test_config_no_ssl(self) -> None:
  1083. config = ConfigDict()
  1084. config.set(b"http", b"sslVerify", b"false")
  1085. manager = default_urllib3_manager(config=config)
  1086. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE")
  1087. def test_config_proxy(self) -> None:
  1088. import urllib3
  1089. config = ConfigDict()
  1090. config.set(b"http", b"proxy", b"http://localhost:3128/")
  1091. manager = default_urllib3_manager(config=config)
  1092. self.assertIsInstance(manager, urllib3.ProxyManager)
  1093. self.assertTrue(hasattr(manager, "proxy"))
  1094. self.assertEqual(manager.proxy.scheme, "http")
  1095. self.assertEqual(manager.proxy.host, "localhost")
  1096. self.assertEqual(manager.proxy.port, 3128)
  1097. def test_environment_proxy(self) -> None:
  1098. import urllib3
  1099. config = ConfigDict()
  1100. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1101. manager = default_urllib3_manager(config=config)
  1102. self.assertIsInstance(manager, urllib3.ProxyManager)
  1103. self.assertTrue(hasattr(manager, "proxy"))
  1104. self.assertEqual(manager.proxy.scheme, "http")
  1105. self.assertEqual(manager.proxy.host, "myproxy")
  1106. self.assertEqual(manager.proxy.port, 8080)
  1107. def test_environment_empty_proxy(self) -> None:
  1108. import urllib3
  1109. config = ConfigDict()
  1110. self.overrideEnv("http_proxy", "")
  1111. manager = default_urllib3_manager(config=config)
  1112. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1113. self.assertIsInstance(manager, urllib3.PoolManager)
  1114. def test_environment_no_proxy_1(self) -> None:
  1115. import urllib3
  1116. config = ConfigDict()
  1117. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1118. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh")
  1119. base_url = "http://xyz.abc.def.gh:8080/path/port"
  1120. manager = default_urllib3_manager(config=config, base_url=base_url)
  1121. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1122. self.assertIsInstance(manager, urllib3.PoolManager)
  1123. def test_environment_no_proxy_2(self) -> None:
  1124. import urllib3
  1125. config = ConfigDict()
  1126. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1127. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1128. base_url = "http://ample.com/path/port"
  1129. manager = default_urllib3_manager(config=config, base_url=base_url)
  1130. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1131. self.assertIsInstance(manager, urllib3.PoolManager)
  1132. def test_environment_no_proxy_3(self) -> None:
  1133. import urllib3
  1134. config = ConfigDict()
  1135. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1136. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1137. base_url = "http://ample.com:80/path/port"
  1138. manager = default_urllib3_manager(config=config, base_url=base_url)
  1139. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1140. self.assertIsInstance(manager, urllib3.PoolManager)
  1141. def test_environment_no_proxy_4(self) -> None:
  1142. import urllib3
  1143. config = ConfigDict()
  1144. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1145. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1146. base_url = "http://www.ample.com/path/port"
  1147. manager = default_urllib3_manager(config=config, base_url=base_url)
  1148. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1149. self.assertIsInstance(manager, urllib3.PoolManager)
  1150. def test_environment_no_proxy_5(self) -> None:
  1151. import urllib3
  1152. config = ConfigDict()
  1153. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1154. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1155. base_url = "http://www.example.com/path/port"
  1156. manager = default_urllib3_manager(config=config, base_url=base_url)
  1157. self.assertIsInstance(manager, urllib3.ProxyManager)
  1158. self.assertTrue(hasattr(manager, "proxy"))
  1159. self.assertEqual(manager.proxy.scheme, "http")
  1160. self.assertEqual(manager.proxy.host, "myproxy")
  1161. self.assertEqual(manager.proxy.port, 8080)
  1162. def test_environment_no_proxy_6(self) -> None:
  1163. import urllib3
  1164. config = ConfigDict()
  1165. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1166. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1167. base_url = "http://ample.com.org/path/port"
  1168. manager = default_urllib3_manager(config=config, base_url=base_url)
  1169. self.assertIsInstance(manager, urllib3.ProxyManager)
  1170. self.assertTrue(hasattr(manager, "proxy"))
  1171. self.assertEqual(manager.proxy.scheme, "http")
  1172. self.assertEqual(manager.proxy.host, "myproxy")
  1173. self.assertEqual(manager.proxy.port, 8080)
  1174. def test_environment_no_proxy_ipv4_address_1(self) -> None:
  1175. import urllib3
  1176. config = ConfigDict()
  1177. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1178. self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com")
  1179. base_url = "http://192.168.0.10/path/port"
  1180. manager = default_urllib3_manager(config=config, base_url=base_url)
  1181. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1182. self.assertIsInstance(manager, urllib3.PoolManager)
  1183. def test_environment_no_proxy_ipv4_address_2(self) -> None:
  1184. import urllib3
  1185. config = ConfigDict()
  1186. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1187. self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com")
  1188. base_url = "http://192.168.0.10:8888/path/port"
  1189. manager = default_urllib3_manager(config=config, base_url=base_url)
  1190. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1191. self.assertIsInstance(manager, urllib3.PoolManager)
  1192. def test_environment_no_proxy_ipv4_address_3(self) -> None:
  1193. import urllib3
  1194. config = ConfigDict()
  1195. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1196. self.overrideEnv(
  1197. "no_proxy", "xyz,abc.def.gh,ff80:1::/64,192.168.0.0/24,ample.com"
  1198. )
  1199. base_url = "http://192.168.0.10/path/port"
  1200. manager = default_urllib3_manager(config=config, base_url=base_url)
  1201. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1202. self.assertIsInstance(manager, urllib3.PoolManager)
  1203. def test_environment_no_proxy_ipv6_address_1(self) -> None:
  1204. import urllib3
  1205. config = ConfigDict()
  1206. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1207. self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com")
  1208. base_url = "http://[ff80:1::affe]/path/port"
  1209. manager = default_urllib3_manager(config=config, base_url=base_url)
  1210. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1211. self.assertIsInstance(manager, urllib3.PoolManager)
  1212. def test_environment_no_proxy_ipv6_address_2(self) -> None:
  1213. import urllib3
  1214. config = ConfigDict()
  1215. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1216. self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com")
  1217. base_url = "http://[ff80:1::affe]:1234/path/port"
  1218. manager = default_urllib3_manager(config=config, base_url=base_url)
  1219. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1220. self.assertIsInstance(manager, urllib3.PoolManager)
  1221. def test_environment_no_proxy_ipv6_address_3(self) -> None:
  1222. import urllib3
  1223. config = ConfigDict()
  1224. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1225. self.overrideEnv(
  1226. "no_proxy", "xyz,abc.def.gh,192.168.0.0/24,ff80:1::/64,ample.com"
  1227. )
  1228. base_url = "http://[ff80:1::affe]/path/port"
  1229. manager = default_urllib3_manager(config=config, base_url=base_url)
  1230. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1231. self.assertIsInstance(manager, urllib3.PoolManager)
  1232. def test_config_proxy_custom_cls(self) -> None:
  1233. import urllib3
  1234. class CustomProxyManager(urllib3.ProxyManager):
  1235. pass
  1236. config = ConfigDict()
  1237. config.set(b"http", b"proxy", b"http://localhost:3128/")
  1238. manager = default_urllib3_manager(
  1239. config=config, proxy_manager_cls=CustomProxyManager
  1240. )
  1241. self.assertIsInstance(manager, CustomProxyManager)
  1242. def test_config_proxy_creds(self) -> None:
  1243. import urllib3
  1244. config = ConfigDict()
  1245. config.set(b"http", b"proxy", b"http://jelmer:example@localhost:3128/")
  1246. manager = default_urllib3_manager(config=config)
  1247. assert isinstance(manager, urllib3.ProxyManager)
  1248. self.assertEqual(
  1249. manager.proxy_headers, {"proxy-authorization": "Basic amVsbWVyOmV4YW1wbGU="}
  1250. )
  1251. def test_config_no_verify_ssl(self) -> None:
  1252. manager = default_urllib3_manager(config=None, cert_reqs="CERT_NONE")
  1253. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE")
  1254. class SubprocessSSHVendorTests(TestCase):
  1255. def setUp(self) -> None:
  1256. # Monkey Patch client subprocess popen
  1257. self._orig_popen = dulwich.client.subprocess.Popen
  1258. dulwich.client.subprocess.Popen = DummyPopen
  1259. def tearDown(self) -> None:
  1260. dulwich.client.subprocess.Popen = self._orig_popen
  1261. def test_run_command_dashes(self) -> None:
  1262. vendor = SubprocessSSHVendor()
  1263. self.assertRaises(
  1264. StrangeHostname,
  1265. vendor.run_command,
  1266. "--weird-host",
  1267. "git-clone-url",
  1268. )
  1269. def test_run_command_password(self) -> None:
  1270. vendor = SubprocessSSHVendor()
  1271. self.assertRaises(
  1272. NotImplementedError,
  1273. vendor.run_command,
  1274. "host",
  1275. "git-clone-url",
  1276. password="12345",
  1277. )
  1278. def test_run_command_password_and_privkey(self) -> None:
  1279. vendor = SubprocessSSHVendor()
  1280. self.assertRaises(
  1281. NotImplementedError,
  1282. vendor.run_command,
  1283. "host",
  1284. "git-clone-url",
  1285. password="12345",
  1286. key_filename="/tmp/id_rsa",
  1287. )
  1288. def test_run_command_with_port_username_and_privkey(self) -> None:
  1289. expected = [
  1290. "ssh",
  1291. "-x",
  1292. "-p",
  1293. "2200",
  1294. "-i",
  1295. "/tmp/id_rsa",
  1296. ]
  1297. if DEFAULT_GIT_PROTOCOL_VERSION_FETCH:
  1298. expected += [
  1299. "-o",
  1300. f"SetEnv GIT_PROTOCOL=version={DEFAULT_GIT_PROTOCOL_VERSION_FETCH}",
  1301. ]
  1302. expected += [
  1303. "user@host",
  1304. "git-clone-url",
  1305. ]
  1306. vendor = SubprocessSSHVendor()
  1307. command = vendor.run_command(
  1308. "host",
  1309. "git-clone-url",
  1310. username="user",
  1311. port="2200",
  1312. key_filename="/tmp/id_rsa",
  1313. )
  1314. args = command.proc.args
  1315. self.assertListEqual(expected, args[0])
  1316. def test_run_with_ssh_command(self) -> None:
  1317. expected = [
  1318. "/path/to/ssh",
  1319. "-o",
  1320. "Option=Value",
  1321. "-x",
  1322. ]
  1323. if DEFAULT_GIT_PROTOCOL_VERSION_FETCH:
  1324. expected += [
  1325. "-o",
  1326. f"SetEnv GIT_PROTOCOL=version={DEFAULT_GIT_PROTOCOL_VERSION_FETCH}",
  1327. ]
  1328. expected += [
  1329. "host",
  1330. "git-clone-url",
  1331. ]
  1332. vendor = SubprocessSSHVendor()
  1333. command = vendor.run_command(
  1334. "host",
  1335. "git-clone-url",
  1336. ssh_command="/path/to/ssh -o Option=Value",
  1337. )
  1338. args = command.proc.args
  1339. self.assertListEqual(expected, args[0])
  1340. class PLinkSSHVendorTests(TestCase):
  1341. def setUp(self) -> None:
  1342. # Monkey Patch client subprocess popen
  1343. self._orig_popen = dulwich.client.subprocess.Popen
  1344. dulwich.client.subprocess.Popen = DummyPopen
  1345. def tearDown(self) -> None:
  1346. dulwich.client.subprocess.Popen = self._orig_popen
  1347. def test_run_command_dashes(self) -> None:
  1348. vendor = PLinkSSHVendor()
  1349. self.assertRaises(
  1350. StrangeHostname,
  1351. vendor.run_command,
  1352. "--weird-host",
  1353. "git-clone-url",
  1354. )
  1355. def test_run_command_password_and_privkey(self) -> None:
  1356. vendor = PLinkSSHVendor()
  1357. warnings.simplefilter("always", UserWarning)
  1358. self.addCleanup(warnings.resetwarnings)
  1359. warnings_list, restore_warnings = setup_warning_catcher()
  1360. self.addCleanup(restore_warnings)
  1361. command = vendor.run_command(
  1362. "host",
  1363. "git-clone-url",
  1364. password="12345",
  1365. key_filename="/tmp/id_rsa",
  1366. )
  1367. expected_warning = UserWarning(
  1368. "Invoking PLink with a password exposes the password in the "
  1369. "process list."
  1370. )
  1371. for w in warnings_list:
  1372. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  1373. break
  1374. else:
  1375. raise AssertionError(
  1376. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  1377. )
  1378. args = command.proc.args
  1379. if sys.platform == "win32":
  1380. binary = ["plink.exe", "-ssh"]
  1381. else:
  1382. binary = ["plink", "-ssh"]
  1383. expected = [
  1384. *binary,
  1385. "-pw",
  1386. "12345",
  1387. "-i",
  1388. "/tmp/id_rsa",
  1389. "host",
  1390. "git-clone-url",
  1391. ]
  1392. self.assertListEqual(expected, args[0])
  1393. def test_run_command_password(self) -> None:
  1394. if sys.platform == "win32":
  1395. binary = ["plink.exe", "-ssh"]
  1396. else:
  1397. binary = ["plink", "-ssh"]
  1398. expected = [*binary, "-pw", "12345", "host", "git-clone-url"]
  1399. vendor = PLinkSSHVendor()
  1400. warnings.simplefilter("always", UserWarning)
  1401. self.addCleanup(warnings.resetwarnings)
  1402. warnings_list, restore_warnings = setup_warning_catcher()
  1403. self.addCleanup(restore_warnings)
  1404. command = vendor.run_command("host", "git-clone-url", password="12345")
  1405. expected_warning = UserWarning(
  1406. "Invoking PLink with a password exposes the password in the "
  1407. "process list."
  1408. )
  1409. for w in warnings_list:
  1410. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  1411. break
  1412. else:
  1413. raise AssertionError(
  1414. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  1415. )
  1416. args = command.proc.args
  1417. self.assertListEqual(expected, args[0])
  1418. def test_run_command_with_port_username_and_privkey(self) -> None:
  1419. if sys.platform == "win32":
  1420. binary = ["plink.exe", "-ssh"]
  1421. else:
  1422. binary = ["plink", "-ssh"]
  1423. expected = [
  1424. *binary,
  1425. "-P",
  1426. "2200",
  1427. "-i",
  1428. "/tmp/id_rsa",
  1429. "user@host",
  1430. "git-clone-url",
  1431. ]
  1432. vendor = PLinkSSHVendor()
  1433. command = vendor.run_command(
  1434. "host",
  1435. "git-clone-url",
  1436. username="user",
  1437. port="2200",
  1438. key_filename="/tmp/id_rsa",
  1439. )
  1440. args = command.proc.args
  1441. self.assertListEqual(expected, args[0])
  1442. def test_run_with_ssh_command(self) -> None:
  1443. expected = [
  1444. "/path/to/plink",
  1445. "-ssh",
  1446. "host",
  1447. "git-clone-url",
  1448. ]
  1449. vendor = PLinkSSHVendor()
  1450. command = vendor.run_command(
  1451. "host",
  1452. "git-clone-url",
  1453. ssh_command="/path/to/plink",
  1454. )
  1455. args = command.proc.args
  1456. self.assertListEqual(expected, args[0])
  1457. class RsyncUrlTests(TestCase):
  1458. def test_simple(self) -> None:
  1459. self.assertEqual(parse_rsync_url("foo:bar/path"), (None, "foo", "bar/path"))
  1460. self.assertEqual(
  1461. parse_rsync_url("user@foo:bar/path"), ("user", "foo", "bar/path")
  1462. )
  1463. def test_path(self) -> None:
  1464. self.assertRaises(ValueError, parse_rsync_url, "/path")
  1465. class CheckWantsTests(TestCase):
  1466. def test_fine(self) -> None:
  1467. check_wants(
  1468. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1469. {b"refs/heads/blah": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1470. )
  1471. def test_missing(self) -> None:
  1472. self.assertRaises(
  1473. InvalidWants,
  1474. check_wants,
  1475. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1476. {b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1477. )
  1478. def test_annotated(self) -> None:
  1479. self.assertRaises(
  1480. InvalidWants,
  1481. check_wants,
  1482. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1483. {
  1484. b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262",
  1485. b"refs/heads/blah^{}": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262",
  1486. },
  1487. )
  1488. class FetchPackResultTests(TestCase):
  1489. def test_eq(self) -> None:
  1490. self.assertEqual(
  1491. FetchPackResult(
  1492. {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1493. {},
  1494. b"user/agent",
  1495. ),
  1496. FetchPackResult(
  1497. {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1498. {},
  1499. b"user/agent",
  1500. ),
  1501. )
  1502. class GitCredentialStoreTests(TestCase):
  1503. @classmethod
  1504. def setUpClass(cls) -> None:
  1505. with tempfile.NamedTemporaryFile(delete=False) as f:
  1506. f.write(b"https://user:pass@example.org\n")
  1507. cls.fname = f.name
  1508. @classmethod
  1509. def tearDownClass(cls) -> None:
  1510. os.unlink(cls.fname)
  1511. def test_nonmatching_scheme(self) -> None:
  1512. self.assertEqual(
  1513. get_credentials_from_store(b"http", b"example.org", fnames=[self.fname]),
  1514. None,
  1515. )
  1516. def test_nonmatching_hostname(self) -> None:
  1517. self.assertEqual(
  1518. get_credentials_from_store(b"https", b"noentry.org", fnames=[self.fname]),
  1519. None,
  1520. )
  1521. def test_match_without_username(self) -> None:
  1522. self.assertEqual(
  1523. get_credentials_from_store(b"https", b"example.org", fnames=[self.fname]),
  1524. (b"user", b"pass"),
  1525. )
  1526. def test_match_with_matching_username(self) -> None:
  1527. self.assertEqual(
  1528. get_credentials_from_store(
  1529. b"https", b"example.org", b"user", fnames=[self.fname]
  1530. ),
  1531. (b"user", b"pass"),
  1532. )
  1533. def test_no_match_with_nonmatching_username(self) -> None:
  1534. self.assertEqual(
  1535. get_credentials_from_store(
  1536. b"https", b"example.org", b"otheruser", fnames=[self.fname]
  1537. ),
  1538. None,
  1539. )
  1540. class RemoteErrorFromStderrTests(TestCase):
  1541. def test_nothing(self) -> None:
  1542. self.assertEqual(_remote_error_from_stderr(None), HangupException())
  1543. def test_error_line(self) -> None:
  1544. b = BytesIO(
  1545. b"""\
  1546. This is some random output.
  1547. ERROR: This is the actual error
  1548. with a tail
  1549. """
  1550. )
  1551. self.assertEqual(
  1552. _remote_error_from_stderr(b),
  1553. GitProtocolError("This is the actual error"),
  1554. )
  1555. def test_no_error_line(self) -> None:
  1556. b = BytesIO(
  1557. b"""\
  1558. This is output without an error line.
  1559. And this line is just random noise, too.
  1560. """
  1561. )
  1562. self.assertEqual(
  1563. _remote_error_from_stderr(b),
  1564. HangupException(
  1565. [
  1566. b"This is output without an error line.",
  1567. b"And this line is just random noise, too.",
  1568. ]
  1569. ),
  1570. )
  1571. class TestExtractAgentAndSymrefs(TestCase):
  1572. def test_extract_agent_and_symrefs(self) -> None:
  1573. (symrefs, agent) = _extract_symrefs_and_agent(
  1574. [b"agent=git/2.31.1", b"symref=HEAD:refs/heads/master"]
  1575. )
  1576. self.assertEqual(agent, b"git/2.31.1")
  1577. self.assertEqual(symrefs, {b"HEAD": b"refs/heads/master"})