test_client.py 66 KB

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