test_client.py 65 KB

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