test_client.py 66 KB

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