test_client.py 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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 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):
  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. ):
  615. self.host = host
  616. self.command = command
  617. self.username = username
  618. self.port = port
  619. self.password = password
  620. self.key_filename = key_filename
  621. self.ssh_command = ssh_command
  622. class Subprocess:
  623. pass
  624. Subprocess.read = lambda: None
  625. Subprocess.write = lambda: None
  626. Subprocess.close = lambda: None
  627. Subprocess.can_read = lambda: None
  628. return Subprocess()
  629. class SSHGitClientTests(TestCase):
  630. def setUp(self):
  631. super().setUp()
  632. self.server = TestSSHVendor()
  633. self.real_vendor = client.get_ssh_vendor
  634. client.get_ssh_vendor = lambda: self.server
  635. self.client = SSHGitClient("git.samba.org")
  636. def tearDown(self):
  637. super().tearDown()
  638. client.get_ssh_vendor = self.real_vendor
  639. def test_get_url(self):
  640. path = "/tmp/repo.git"
  641. c = SSHGitClient("git.samba.org")
  642. url = c.get_url(path)
  643. self.assertEqual("ssh://git.samba.org/tmp/repo.git", url)
  644. def test_get_url_with_username_and_port(self):
  645. path = "/tmp/repo.git"
  646. c = SSHGitClient("git.samba.org", port=2222, username="user")
  647. url = c.get_url(path)
  648. self.assertEqual("ssh://user@git.samba.org:2222/tmp/repo.git", url)
  649. def test_default_command(self):
  650. self.assertEqual(b"git-upload-pack", self.client._get_cmd_path(b"upload-pack"))
  651. def test_alternative_command_path(self):
  652. self.client.alternative_paths[b"upload-pack"] = b"/usr/lib/git/git-upload-pack"
  653. self.assertEqual(
  654. b"/usr/lib/git/git-upload-pack",
  655. self.client._get_cmd_path(b"upload-pack"),
  656. )
  657. def test_alternative_command_path_spaces(self):
  658. self.client.alternative_paths[b"upload-pack"] = (
  659. b"/usr/lib/git/git-upload-pack -ibla"
  660. )
  661. self.assertEqual(
  662. b"/usr/lib/git/git-upload-pack -ibla",
  663. self.client._get_cmd_path(b"upload-pack"),
  664. )
  665. def test_connect(self):
  666. server = self.server
  667. client = self.client
  668. client.username = b"username"
  669. client.port = 1337
  670. client._connect(b"command", b"/path/to/repo")
  671. self.assertEqual(b"username", server.username)
  672. self.assertEqual(1337, server.port)
  673. self.assertEqual("git-command '/path/to/repo'", server.command)
  674. client._connect(b"relative-command", b"/~/path/to/repo")
  675. self.assertEqual("git-relative-command '~/path/to/repo'", server.command)
  676. def test_ssh_command_precedence(self):
  677. self.overrideEnv("GIT_SSH", "/path/to/ssh")
  678. test_client = SSHGitClient("git.samba.org")
  679. self.assertEqual(test_client.ssh_command, "/path/to/ssh")
  680. self.overrideEnv("GIT_SSH_COMMAND", "/path/to/ssh -o Option=Value")
  681. test_client = SSHGitClient("git.samba.org")
  682. self.assertEqual(test_client.ssh_command, "/path/to/ssh -o Option=Value")
  683. test_client = SSHGitClient("git.samba.org", ssh_command="ssh -o Option1=Value1")
  684. self.assertEqual(test_client.ssh_command, "ssh -o Option1=Value1")
  685. class ReportStatusParserTests(TestCase):
  686. def test_invalid_pack(self):
  687. parser = ReportStatusParser()
  688. parser.handle_packet(b"unpack error - foo bar")
  689. parser.handle_packet(b"ok refs/foo/bar")
  690. parser.handle_packet(None)
  691. self.assertRaises(SendPackError, list, parser.check())
  692. def test_update_refs_error(self):
  693. parser = ReportStatusParser()
  694. parser.handle_packet(b"unpack ok")
  695. parser.handle_packet(b"ng refs/foo/bar need to pull")
  696. parser.handle_packet(None)
  697. self.assertEqual([(b"refs/foo/bar", "need to pull")], list(parser.check()))
  698. def test_ok(self):
  699. parser = ReportStatusParser()
  700. parser.handle_packet(b"unpack ok")
  701. parser.handle_packet(b"ok refs/foo/bar")
  702. parser.handle_packet(None)
  703. self.assertEqual([(b"refs/foo/bar", None)], list(parser.check()))
  704. class LocalGitClientTests(TestCase):
  705. def test_get_url(self):
  706. path = "/tmp/repo.git"
  707. c = LocalGitClient()
  708. url = c.get_url(path)
  709. self.assertEqual("file:///tmp/repo.git", url)
  710. def test_fetch_into_empty(self):
  711. c = LocalGitClient()
  712. target = tempfile.mkdtemp()
  713. self.addCleanup(shutil.rmtree, target)
  714. t = Repo.init_bare(target)
  715. self.addCleanup(t.close)
  716. s = open_repo("a.git")
  717. self.addCleanup(tear_down_repo, s)
  718. self.assertEqual(s.get_refs(), c.fetch(s.path, t).refs)
  719. def test_clone(self):
  720. c = LocalGitClient()
  721. s = open_repo("a.git")
  722. self.addCleanup(tear_down_repo, s)
  723. target = tempfile.mkdtemp()
  724. self.addCleanup(shutil.rmtree, target)
  725. result_repo = c.clone(s.path, target, mkdir=False)
  726. self.addCleanup(result_repo.close)
  727. expected = dict(s.get_refs())
  728. expected[b"refs/remotes/origin/HEAD"] = expected[b"HEAD"]
  729. expected[b"refs/remotes/origin/master"] = expected[b"refs/heads/master"]
  730. self.assertEqual(expected, result_repo.get_refs())
  731. def test_fetch_empty(self):
  732. c = LocalGitClient()
  733. s = open_repo("a.git")
  734. self.addCleanup(tear_down_repo, s)
  735. out = BytesIO()
  736. walker = {}
  737. ret = c.fetch_pack(
  738. s.path, lambda heads, **kwargs: [], graph_walker=walker, pack_data=out.write
  739. )
  740. self.assertEqual(
  741. {
  742. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  743. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  744. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  745. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  746. },
  747. ret.refs,
  748. )
  749. self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs)
  750. self.assertEqual(
  751. b"PACK\x00\x00\x00\x02\x00\x00\x00\x00\x02\x9d\x08"
  752. b"\x82;\xd8\xa8\xea\xb5\x10\xadj\xc7\\\x82<\xfd>\xd3\x1e",
  753. out.getvalue(),
  754. )
  755. def test_fetch_pack_none(self):
  756. c = LocalGitClient()
  757. s = open_repo("a.git")
  758. self.addCleanup(tear_down_repo, s)
  759. out = BytesIO()
  760. walker = MemoryRepo().get_graph_walker()
  761. ret = c.fetch_pack(
  762. s.path,
  763. lambda heads, **kwargs: [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  764. graph_walker=walker,
  765. pack_data=out.write,
  766. )
  767. self.assertEqual({b"HEAD": b"refs/heads/master"}, ret.symrefs)
  768. self.assertEqual(
  769. {
  770. b"HEAD": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  771. b"refs/heads/master": b"a90fa2d900a17e99b433217e988c4eb4a2e9a097",
  772. b"refs/tags/mytag": b"28237f4dc30d0d462658d6b937b08a0f0b6ef55a",
  773. b"refs/tags/mytag-packed": b"b0931cadc54336e78a1d980420e3268903b57a50",
  774. },
  775. ret.refs,
  776. )
  777. # Hardcoding is not ideal, but we'll fix that some other day..
  778. self.assertTrue(
  779. out.getvalue().startswith(b"PACK\x00\x00\x00\x02\x00\x00\x00\x07")
  780. )
  781. def test_send_pack_without_changes(self):
  782. local = open_repo("a.git")
  783. self.addCleanup(tear_down_repo, local)
  784. target = open_repo("a.git")
  785. self.addCleanup(tear_down_repo, target)
  786. self.send_and_verify(b"master", local, target)
  787. def test_send_pack_with_changes(self):
  788. local = open_repo("a.git")
  789. self.addCleanup(tear_down_repo, local)
  790. target_path = tempfile.mkdtemp()
  791. self.addCleanup(shutil.rmtree, target_path)
  792. with Repo.init_bare(target_path) as target:
  793. self.send_and_verify(b"master", local, target)
  794. def test_get_refs(self):
  795. local = open_repo("refs.git")
  796. self.addCleanup(tear_down_repo, local)
  797. client = LocalGitClient()
  798. refs = client.get_refs(local.path)
  799. self.assertDictEqual(local.refs.as_dict(), refs)
  800. def send_and_verify(self, branch, local, target):
  801. """Send branch from local to remote repository and verify it worked."""
  802. client = LocalGitClient()
  803. ref_name = b"refs/heads/" + branch
  804. result = client.send_pack(
  805. target.path,
  806. lambda _: {ref_name: local.refs[ref_name]},
  807. local.generate_pack_data,
  808. )
  809. self.assertEqual(local.refs[ref_name], result.refs[ref_name])
  810. self.assertIs(None, result.agent)
  811. self.assertEqual({}, result.ref_status)
  812. obj_local = local.get_object(result.refs[ref_name])
  813. obj_target = target.get_object(result.refs[ref_name])
  814. self.assertEqual(obj_local, obj_target)
  815. class HttpGitClientTests(TestCase):
  816. def test_get_url(self):
  817. base_url = "https://github.com/jelmer/dulwich"
  818. path = "/jelmer/dulwich"
  819. c = HttpGitClient(base_url)
  820. url = c.get_url(path)
  821. self.assertEqual("https://github.com/jelmer/dulwich", url)
  822. def test_get_url_bytes_path(self):
  823. base_url = "https://github.com/jelmer/dulwich"
  824. path_bytes = b"/jelmer/dulwich"
  825. c = HttpGitClient(base_url)
  826. url = c.get_url(path_bytes)
  827. self.assertEqual("https://github.com/jelmer/dulwich", url)
  828. def test_get_url_with_username_and_passwd(self):
  829. base_url = "https://github.com/jelmer/dulwich"
  830. path = "/jelmer/dulwich"
  831. c = HttpGitClient(base_url, username="USERNAME", password="PASSWD")
  832. url = c.get_url(path)
  833. self.assertEqual("https://github.com/jelmer/dulwich", url)
  834. def test_init_username_passwd_set(self):
  835. url = "https://github.com/jelmer/dulwich"
  836. c = HttpGitClient(url, config=None, username="user", password="passwd")
  837. self.assertEqual("user", c._username)
  838. self.assertEqual("passwd", c._password)
  839. basic_auth = c.pool_manager.headers["authorization"]
  840. auth_string = "{}:{}".format("user", "passwd")
  841. b64_credentials = base64.b64encode(auth_string.encode("latin1"))
  842. expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1"))
  843. self.assertEqual(basic_auth, expected_basic_auth)
  844. def test_init_username_set_no_password(self):
  845. url = "https://github.com/jelmer/dulwich"
  846. c = HttpGitClient(url, config=None, username="user")
  847. self.assertEqual("user", c._username)
  848. self.assertIsNone(c._password)
  849. basic_auth = c.pool_manager.headers["authorization"]
  850. auth_string = b"user:"
  851. b64_credentials = base64.b64encode(auth_string)
  852. expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}"
  853. self.assertEqual(basic_auth, expected_basic_auth)
  854. def test_init_no_username_passwd(self):
  855. url = "https://github.com/jelmer/dulwich"
  856. c = HttpGitClient(url, config=None)
  857. self.assertIs(None, c._username)
  858. self.assertIs(None, c._password)
  859. self.assertNotIn("authorization", c.pool_manager.headers)
  860. def test_from_parsedurl_username_only(self):
  861. username = "user"
  862. url = f"https://{username}@github.com/jelmer/dulwich"
  863. c = HttpGitClient.from_parsedurl(urlparse(url))
  864. self.assertEqual(c._username, username)
  865. self.assertEqual(c._password, None)
  866. basic_auth = c.pool_manager.headers["authorization"]
  867. auth_string = username.encode("ascii") + b":"
  868. b64_credentials = base64.b64encode(auth_string)
  869. expected_basic_auth = f"Basic {b64_credentials.decode('ascii')}"
  870. self.assertEqual(basic_auth, expected_basic_auth)
  871. def test_from_parsedurl_on_url_with_quoted_credentials(self):
  872. original_username = "john|the|first"
  873. quoted_username = urlquote(original_username)
  874. original_password = "Ya#1$2%3"
  875. quoted_password = urlquote(original_password)
  876. url = f"https://{quoted_username}:{quoted_password}@github.com/jelmer/dulwich"
  877. c = HttpGitClient.from_parsedurl(urlparse(url))
  878. self.assertEqual(original_username, c._username)
  879. self.assertEqual(original_password, c._password)
  880. basic_auth = c.pool_manager.headers["authorization"]
  881. auth_string = f"{original_username}:{original_password}"
  882. b64_credentials = base64.b64encode(auth_string.encode("latin1"))
  883. expected_basic_auth = "Basic {}".format(b64_credentials.decode("latin1"))
  884. self.assertEqual(basic_auth, expected_basic_auth)
  885. def test_url_redirect_location(self):
  886. from urllib3.response import HTTPResponse
  887. test_data = {
  888. "https://gitlab.com/inkscape/inkscape/": {
  889. "location": "https://gitlab.com/inkscape/inkscape.git/",
  890. "redirect_url": "https://gitlab.com/inkscape/inkscape.git/",
  891. "refs_data": (
  892. b"001e# service=git-upload-pack\n00000032"
  893. b"fb2bebf4919a011f0fd7cec085443d0031228e76 "
  894. b"HEAD\n0000"
  895. ),
  896. },
  897. "https://github.com/jelmer/dulwich/": {
  898. "location": "https://github.com/jelmer/dulwich/",
  899. "redirect_url": "https://github.com/jelmer/dulwich/",
  900. "refs_data": (
  901. b"001e# service=git-upload-pack\n00000032"
  902. b"3ff25e09724aa4d86ea5bca7d5dd0399a3c8bfcf "
  903. b"HEAD\n0000"
  904. ),
  905. },
  906. # check for absolute-path URI reference as location
  907. "https://codeberg.org/ashwinvis/radicale-sh.git/": {
  908. "location": "/ashwinvis/radicale-auth-sh/",
  909. "redirect_url": "https://codeberg.org/ashwinvis/radicale-auth-sh/",
  910. "refs_data": (
  911. b"001e# service=git-upload-pack\n00000032"
  912. b"470f8603768b608fc988675de2fae8f963c21158 "
  913. b"HEAD\n0000"
  914. ),
  915. },
  916. }
  917. tail = "info/refs?service=git-upload-pack"
  918. # we need to mock urllib3.PoolManager as this test will fail
  919. # otherwise without an active internet connection
  920. class PoolManagerMock:
  921. def __init__(self) -> None:
  922. self.headers: Dict[str, str] = {}
  923. def request(
  924. self,
  925. method,
  926. url,
  927. fields=None,
  928. headers=None,
  929. redirect=True,
  930. preload_content=True,
  931. ):
  932. base_url = url[: -len(tail)]
  933. redirect_base_url = test_data[base_url]["location"]
  934. redirect_url = redirect_base_url + tail
  935. headers = {
  936. "Content-Type": "application/x-git-upload-pack-advertisement"
  937. }
  938. body = test_data[base_url]["refs_data"]
  939. # urllib3 handles automatic redirection by default
  940. status = 200
  941. request_url = redirect_url
  942. # simulate urllib3 behavior when redirect parameter is False
  943. if redirect is False:
  944. request_url = url
  945. if redirect_base_url != base_url:
  946. body = b""
  947. headers["location"] = test_data[base_url]["location"]
  948. status = 301
  949. return HTTPResponse(
  950. body=BytesIO(body),
  951. headers=headers,
  952. request_method=method,
  953. request_url=request_url,
  954. preload_content=preload_content,
  955. status=status,
  956. )
  957. pool_manager = PoolManagerMock()
  958. for base_url in test_data.keys():
  959. # instantiate HttpGitClient with mocked pool manager
  960. c = HttpGitClient(base_url, pool_manager=pool_manager, config=None)
  961. # call method that detects url redirection
  962. _, _, processed_url = c._discover_references(b"git-upload-pack", base_url)
  963. # send the same request as the method above without redirection
  964. resp = c.pool_manager.request("GET", base_url + tail, redirect=False)
  965. # check expected behavior of urllib3
  966. redirect_location = resp.get_redirect_location()
  967. if resp.status == 200:
  968. self.assertFalse(redirect_location)
  969. if redirect_location:
  970. # check that url redirection has been correctly detected
  971. self.assertEqual(processed_url, test_data[base_url]["redirect_url"])
  972. else:
  973. # check also the no redirection case
  974. self.assertEqual(processed_url, base_url)
  975. def test_smart_request_content_type_with_directive_check(self):
  976. from urllib3.response import HTTPResponse
  977. # we need to mock urllib3.PoolManager as this test will fail
  978. # otherwise without an active internet connection
  979. class PoolManagerMock:
  980. def __init__(self) -> None:
  981. self.headers: Dict[str, str] = {}
  982. def request(
  983. self,
  984. method,
  985. url,
  986. fields=None,
  987. headers=None,
  988. redirect=True,
  989. preload_content=True,
  990. ):
  991. return HTTPResponse(
  992. headers={
  993. "Content-Type": "application/x-git-upload-pack-result; charset=utf-8"
  994. },
  995. request_method=method,
  996. request_url=url,
  997. preload_content=preload_content,
  998. status=200,
  999. )
  1000. clone_url = "https://hacktivis.me/git/blog.git/"
  1001. client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None)
  1002. self.assertTrue(client._smart_request("git-upload-pack", clone_url, data=None))
  1003. def test_urllib3_protocol_error(self):
  1004. from urllib3.exceptions import ProtocolError
  1005. from urllib3.response import HTTPResponse
  1006. error_msg = "protocol error"
  1007. # we need to mock urllib3.PoolManager as this test will fail
  1008. # otherwise without an active internet connection
  1009. class PoolManagerMock:
  1010. def __init__(self) -> None:
  1011. self.headers: Dict[str, str] = {}
  1012. def request(
  1013. self,
  1014. method,
  1015. url,
  1016. fields=None,
  1017. headers=None,
  1018. redirect=True,
  1019. preload_content=True,
  1020. ):
  1021. response = HTTPResponse(
  1022. headers={"Content-Type": "application/x-git-upload-pack-result"},
  1023. request_method=method,
  1024. request_url=url,
  1025. preload_content=preload_content,
  1026. status=200,
  1027. )
  1028. def read(self):
  1029. raise ProtocolError(error_msg)
  1030. # override HTTPResponse.read to throw urllib3.exceptions.ProtocolError
  1031. response.read = read
  1032. return response
  1033. def check_heads(heads, **kwargs):
  1034. self.assertEqual(heads, {})
  1035. return []
  1036. clone_url = "https://git.example.org/user/project.git/"
  1037. client = HttpGitClient(clone_url, pool_manager=PoolManagerMock(), config=None)
  1038. with self.assertRaises(GitProtocolError, msg=error_msg):
  1039. client.fetch_pack(b"/", check_heads, None, None)
  1040. class TCPGitClientTests(TestCase):
  1041. def test_get_url(self):
  1042. host = "github.com"
  1043. path = "/jelmer/dulwich"
  1044. c = TCPGitClient(host)
  1045. url = c.get_url(path)
  1046. self.assertEqual("git://github.com/jelmer/dulwich", url)
  1047. def test_get_url_with_port(self):
  1048. host = "github.com"
  1049. path = "/jelmer/dulwich"
  1050. port = 9090
  1051. c = TCPGitClient(host, port=port)
  1052. url = c.get_url(path)
  1053. self.assertEqual("git://github.com:9090/jelmer/dulwich", url)
  1054. class DefaultUrllib3ManagerTest(TestCase):
  1055. def test_no_config(self):
  1056. manager = default_urllib3_manager(config=None)
  1057. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED")
  1058. def test_config_no_proxy(self):
  1059. import urllib3
  1060. manager = default_urllib3_manager(config=ConfigDict())
  1061. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1062. self.assertIsInstance(manager, urllib3.PoolManager)
  1063. def test_config_no_proxy_custom_cls(self):
  1064. import urllib3
  1065. class CustomPoolManager(urllib3.PoolManager):
  1066. pass
  1067. manager = default_urllib3_manager(
  1068. config=ConfigDict(), pool_manager_cls=CustomPoolManager
  1069. )
  1070. self.assertIsInstance(manager, CustomPoolManager)
  1071. def test_config_ssl(self):
  1072. config = ConfigDict()
  1073. config.set(b"http", b"sslVerify", b"true")
  1074. manager = default_urllib3_manager(config=config)
  1075. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_REQUIRED")
  1076. def test_config_no_ssl(self):
  1077. config = ConfigDict()
  1078. config.set(b"http", b"sslVerify", b"false")
  1079. manager = default_urllib3_manager(config=config)
  1080. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE")
  1081. def test_config_proxy(self):
  1082. import urllib3
  1083. config = ConfigDict()
  1084. config.set(b"http", b"proxy", b"http://localhost:3128/")
  1085. manager = default_urllib3_manager(config=config)
  1086. self.assertIsInstance(manager, urllib3.ProxyManager)
  1087. self.assertTrue(hasattr(manager, "proxy"))
  1088. self.assertEqual(manager.proxy.scheme, "http")
  1089. self.assertEqual(manager.proxy.host, "localhost")
  1090. self.assertEqual(manager.proxy.port, 3128)
  1091. def test_environment_proxy(self):
  1092. import urllib3
  1093. config = ConfigDict()
  1094. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1095. manager = default_urllib3_manager(config=config)
  1096. self.assertIsInstance(manager, urllib3.ProxyManager)
  1097. self.assertTrue(hasattr(manager, "proxy"))
  1098. self.assertEqual(manager.proxy.scheme, "http")
  1099. self.assertEqual(manager.proxy.host, "myproxy")
  1100. self.assertEqual(manager.proxy.port, 8080)
  1101. def test_environment_empty_proxy(self):
  1102. import urllib3
  1103. config = ConfigDict()
  1104. self.overrideEnv("http_proxy", "")
  1105. manager = default_urllib3_manager(config=config)
  1106. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1107. self.assertIsInstance(manager, urllib3.PoolManager)
  1108. def test_environment_no_proxy_1(self):
  1109. import urllib3
  1110. config = ConfigDict()
  1111. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1112. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh")
  1113. base_url = "http://xyz.abc.def.gh:8080/path/port"
  1114. manager = default_urllib3_manager(config=config, base_url=base_url)
  1115. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1116. self.assertIsInstance(manager, urllib3.PoolManager)
  1117. def test_environment_no_proxy_2(self):
  1118. import urllib3
  1119. config = ConfigDict()
  1120. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1121. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1122. base_url = "http://ample.com/path/port"
  1123. manager = default_urllib3_manager(config=config, base_url=base_url)
  1124. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1125. self.assertIsInstance(manager, urllib3.PoolManager)
  1126. def test_environment_no_proxy_3(self):
  1127. import urllib3
  1128. config = ConfigDict()
  1129. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1130. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1131. base_url = "http://ample.com:80/path/port"
  1132. manager = default_urllib3_manager(config=config, base_url=base_url)
  1133. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1134. self.assertIsInstance(manager, urllib3.PoolManager)
  1135. def test_environment_no_proxy_4(self):
  1136. import urllib3
  1137. config = ConfigDict()
  1138. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1139. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1140. base_url = "http://www.ample.com/path/port"
  1141. manager = default_urllib3_manager(config=config, base_url=base_url)
  1142. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1143. self.assertIsInstance(manager, urllib3.PoolManager)
  1144. def test_environment_no_proxy_5(self):
  1145. import urllib3
  1146. config = ConfigDict()
  1147. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1148. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1149. base_url = "http://www.example.com/path/port"
  1150. manager = default_urllib3_manager(config=config, base_url=base_url)
  1151. self.assertIsInstance(manager, urllib3.ProxyManager)
  1152. self.assertTrue(hasattr(manager, "proxy"))
  1153. self.assertEqual(manager.proxy.scheme, "http")
  1154. self.assertEqual(manager.proxy.host, "myproxy")
  1155. self.assertEqual(manager.proxy.port, 8080)
  1156. def test_environment_no_proxy_6(self):
  1157. import urllib3
  1158. config = ConfigDict()
  1159. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1160. self.overrideEnv("no_proxy", "xyz,abc.def.gh,abc.gh,ample.com")
  1161. base_url = "http://ample.com.org/path/port"
  1162. manager = default_urllib3_manager(config=config, base_url=base_url)
  1163. self.assertIsInstance(manager, urllib3.ProxyManager)
  1164. self.assertTrue(hasattr(manager, "proxy"))
  1165. self.assertEqual(manager.proxy.scheme, "http")
  1166. self.assertEqual(manager.proxy.host, "myproxy")
  1167. self.assertEqual(manager.proxy.port, 8080)
  1168. def test_environment_no_proxy_ipv4_address_1(self):
  1169. import urllib3
  1170. config = ConfigDict()
  1171. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1172. self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com")
  1173. base_url = "http://192.168.0.10/path/port"
  1174. manager = default_urllib3_manager(config=config, base_url=base_url)
  1175. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1176. self.assertIsInstance(manager, urllib3.PoolManager)
  1177. def test_environment_no_proxy_ipv4_address_2(self):
  1178. import urllib3
  1179. config = ConfigDict()
  1180. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1181. self.overrideEnv("no_proxy", "xyz,abc.def.gh,192.168.0.10,ample.com")
  1182. base_url = "http://192.168.0.10:8888/path/port"
  1183. manager = default_urllib3_manager(config=config, base_url=base_url)
  1184. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1185. self.assertIsInstance(manager, urllib3.PoolManager)
  1186. def test_environment_no_proxy_ipv4_address_3(self):
  1187. import urllib3
  1188. config = ConfigDict()
  1189. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1190. self.overrideEnv(
  1191. "no_proxy", "xyz,abc.def.gh,ff80:1::/64,192.168.0.0/24,ample.com"
  1192. )
  1193. base_url = "http://192.168.0.10/path/port"
  1194. manager = default_urllib3_manager(config=config, base_url=base_url)
  1195. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1196. self.assertIsInstance(manager, urllib3.PoolManager)
  1197. def test_environment_no_proxy_ipv6_address_1(self):
  1198. import urllib3
  1199. config = ConfigDict()
  1200. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1201. self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com")
  1202. base_url = "http://[ff80:1::affe]/path/port"
  1203. manager = default_urllib3_manager(config=config, base_url=base_url)
  1204. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1205. self.assertIsInstance(manager, urllib3.PoolManager)
  1206. def test_environment_no_proxy_ipv6_address_2(self):
  1207. import urllib3
  1208. config = ConfigDict()
  1209. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1210. self.overrideEnv("no_proxy", "xyz,abc.def.gh,ff80:1::affe,ample.com")
  1211. base_url = "http://[ff80:1::affe]:1234/path/port"
  1212. manager = default_urllib3_manager(config=config, base_url=base_url)
  1213. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1214. self.assertIsInstance(manager, urllib3.PoolManager)
  1215. def test_environment_no_proxy_ipv6_address_3(self):
  1216. import urllib3
  1217. config = ConfigDict()
  1218. self.overrideEnv("http_proxy", "http://myproxy:8080")
  1219. self.overrideEnv(
  1220. "no_proxy", "xyz,abc.def.gh,192.168.0.0/24,ff80:1::/64,ample.com"
  1221. )
  1222. base_url = "http://[ff80:1::affe]/path/port"
  1223. manager = default_urllib3_manager(config=config, base_url=base_url)
  1224. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  1225. self.assertIsInstance(manager, urllib3.PoolManager)
  1226. def test_config_proxy_custom_cls(self):
  1227. import urllib3
  1228. class CustomProxyManager(urllib3.ProxyManager):
  1229. pass
  1230. config = ConfigDict()
  1231. config.set(b"http", b"proxy", b"http://localhost:3128/")
  1232. manager = default_urllib3_manager(
  1233. config=config, proxy_manager_cls=CustomProxyManager
  1234. )
  1235. self.assertIsInstance(manager, CustomProxyManager)
  1236. def test_config_proxy_creds(self):
  1237. import urllib3
  1238. config = ConfigDict()
  1239. config.set(b"http", b"proxy", b"http://jelmer:example@localhost:3128/")
  1240. manager = default_urllib3_manager(config=config)
  1241. assert isinstance(manager, urllib3.ProxyManager)
  1242. self.assertEqual(
  1243. manager.proxy_headers, {"proxy-authorization": "Basic amVsbWVyOmV4YW1wbGU="}
  1244. )
  1245. def test_config_no_verify_ssl(self):
  1246. manager = default_urllib3_manager(config=None, cert_reqs="CERT_NONE")
  1247. self.assertEqual(manager.connection_pool_kw["cert_reqs"], "CERT_NONE")
  1248. class SubprocessSSHVendorTests(TestCase):
  1249. def setUp(self):
  1250. # Monkey Patch client subprocess popen
  1251. self._orig_popen = dulwich.client.subprocess.Popen
  1252. dulwich.client.subprocess.Popen = DummyPopen
  1253. def tearDown(self):
  1254. dulwich.client.subprocess.Popen = self._orig_popen
  1255. def test_run_command_dashes(self):
  1256. vendor = SubprocessSSHVendor()
  1257. self.assertRaises(
  1258. StrangeHostname,
  1259. vendor.run_command,
  1260. "--weird-host",
  1261. "git-clone-url",
  1262. )
  1263. def test_run_command_password(self):
  1264. vendor = SubprocessSSHVendor()
  1265. self.assertRaises(
  1266. NotImplementedError,
  1267. vendor.run_command,
  1268. "host",
  1269. "git-clone-url",
  1270. password="12345",
  1271. )
  1272. def test_run_command_password_and_privkey(self):
  1273. vendor = SubprocessSSHVendor()
  1274. self.assertRaises(
  1275. NotImplementedError,
  1276. vendor.run_command,
  1277. "host",
  1278. "git-clone-url",
  1279. password="12345",
  1280. key_filename="/tmp/id_rsa",
  1281. )
  1282. def test_run_command_with_port_username_and_privkey(self):
  1283. expected = [
  1284. "ssh",
  1285. "-x",
  1286. "-p",
  1287. "2200",
  1288. "-i",
  1289. "/tmp/id_rsa",
  1290. "user@host",
  1291. "git-clone-url",
  1292. ]
  1293. vendor = SubprocessSSHVendor()
  1294. command = vendor.run_command(
  1295. "host",
  1296. "git-clone-url",
  1297. username="user",
  1298. port="2200",
  1299. key_filename="/tmp/id_rsa",
  1300. )
  1301. args = command.proc.args
  1302. self.assertListEqual(expected, args[0])
  1303. def test_run_with_ssh_command(self):
  1304. expected = [
  1305. "/path/to/ssh",
  1306. "-o",
  1307. "Option=Value",
  1308. "-x",
  1309. "host",
  1310. "git-clone-url",
  1311. ]
  1312. vendor = SubprocessSSHVendor()
  1313. command = vendor.run_command(
  1314. "host",
  1315. "git-clone-url",
  1316. ssh_command="/path/to/ssh -o Option=Value",
  1317. )
  1318. args = command.proc.args
  1319. self.assertListEqual(expected, args[0])
  1320. class PLinkSSHVendorTests(TestCase):
  1321. def setUp(self):
  1322. # Monkey Patch client subprocess popen
  1323. self._orig_popen = dulwich.client.subprocess.Popen
  1324. dulwich.client.subprocess.Popen = DummyPopen
  1325. def tearDown(self):
  1326. dulwich.client.subprocess.Popen = self._orig_popen
  1327. def test_run_command_dashes(self):
  1328. vendor = PLinkSSHVendor()
  1329. self.assertRaises(
  1330. StrangeHostname,
  1331. vendor.run_command,
  1332. "--weird-host",
  1333. "git-clone-url",
  1334. )
  1335. def test_run_command_password_and_privkey(self):
  1336. vendor = PLinkSSHVendor()
  1337. warnings.simplefilter("always", UserWarning)
  1338. self.addCleanup(warnings.resetwarnings)
  1339. warnings_list, restore_warnings = setup_warning_catcher()
  1340. self.addCleanup(restore_warnings)
  1341. command = vendor.run_command(
  1342. "host",
  1343. "git-clone-url",
  1344. password="12345",
  1345. key_filename="/tmp/id_rsa",
  1346. )
  1347. expected_warning = UserWarning(
  1348. "Invoking PLink with a password exposes the password in the "
  1349. "process list."
  1350. )
  1351. for w in warnings_list:
  1352. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  1353. break
  1354. else:
  1355. raise AssertionError(
  1356. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  1357. )
  1358. args = command.proc.args
  1359. if sys.platform == "win32":
  1360. binary = ["plink.exe", "-ssh"]
  1361. else:
  1362. binary = ["plink", "-ssh"]
  1363. expected = [
  1364. *binary,
  1365. "-pw",
  1366. "12345",
  1367. "-i",
  1368. "/tmp/id_rsa",
  1369. "host",
  1370. "git-clone-url",
  1371. ]
  1372. self.assertListEqual(expected, args[0])
  1373. def test_run_command_password(self):
  1374. if sys.platform == "win32":
  1375. binary = ["plink.exe", "-ssh"]
  1376. else:
  1377. binary = ["plink", "-ssh"]
  1378. expected = [*binary, "-pw", "12345", "host", "git-clone-url"]
  1379. vendor = PLinkSSHVendor()
  1380. warnings.simplefilter("always", UserWarning)
  1381. self.addCleanup(warnings.resetwarnings)
  1382. warnings_list, restore_warnings = setup_warning_catcher()
  1383. self.addCleanup(restore_warnings)
  1384. command = vendor.run_command("host", "git-clone-url", password="12345")
  1385. expected_warning = UserWarning(
  1386. "Invoking PLink with a password exposes the password in the "
  1387. "process list."
  1388. )
  1389. for w in warnings_list:
  1390. if type(w) is type(expected_warning) and w.args == expected_warning.args:
  1391. break
  1392. else:
  1393. raise AssertionError(
  1394. f"Expected warning {expected_warning!r} not in {warnings_list!r}"
  1395. )
  1396. args = command.proc.args
  1397. self.assertListEqual(expected, args[0])
  1398. def test_run_command_with_port_username_and_privkey(self):
  1399. if sys.platform == "win32":
  1400. binary = ["plink.exe", "-ssh"]
  1401. else:
  1402. binary = ["plink", "-ssh"]
  1403. expected = [
  1404. *binary,
  1405. "-P",
  1406. "2200",
  1407. "-i",
  1408. "/tmp/id_rsa",
  1409. "user@host",
  1410. "git-clone-url",
  1411. ]
  1412. vendor = PLinkSSHVendor()
  1413. command = vendor.run_command(
  1414. "host",
  1415. "git-clone-url",
  1416. username="user",
  1417. port="2200",
  1418. key_filename="/tmp/id_rsa",
  1419. )
  1420. args = command.proc.args
  1421. self.assertListEqual(expected, args[0])
  1422. def test_run_with_ssh_command(self):
  1423. expected = [
  1424. "/path/to/plink",
  1425. "-x",
  1426. "host",
  1427. "git-clone-url",
  1428. ]
  1429. vendor = SubprocessSSHVendor()
  1430. command = vendor.run_command(
  1431. "host",
  1432. "git-clone-url",
  1433. ssh_command="/path/to/plink",
  1434. )
  1435. args = command.proc.args
  1436. self.assertListEqual(expected, args[0])
  1437. class RsyncUrlTests(TestCase):
  1438. def test_simple(self):
  1439. self.assertEqual(parse_rsync_url("foo:bar/path"), (None, "foo", "bar/path"))
  1440. self.assertEqual(
  1441. parse_rsync_url("user@foo:bar/path"), ("user", "foo", "bar/path")
  1442. )
  1443. def test_path(self):
  1444. self.assertRaises(ValueError, parse_rsync_url, "/path")
  1445. class CheckWantsTests(TestCase):
  1446. def test_fine(self):
  1447. check_wants(
  1448. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1449. {b"refs/heads/blah": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1450. )
  1451. def test_missing(self):
  1452. self.assertRaises(
  1453. InvalidWants,
  1454. check_wants,
  1455. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1456. {b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1457. )
  1458. def test_annotated(self):
  1459. self.assertRaises(
  1460. InvalidWants,
  1461. check_wants,
  1462. [b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"],
  1463. {
  1464. b"refs/heads/blah": b"3f3dc7a53fb752a6961d3a56683df46d4d3bf262",
  1465. b"refs/heads/blah^{}": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262",
  1466. },
  1467. )
  1468. class FetchPackResultTests(TestCase):
  1469. def test_eq(self):
  1470. self.assertEqual(
  1471. FetchPackResult(
  1472. {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1473. {},
  1474. b"user/agent",
  1475. ),
  1476. FetchPackResult(
  1477. {b"refs/heads/master": b"2f3dc7a53fb752a6961d3a56683df46d4d3bf262"},
  1478. {},
  1479. b"user/agent",
  1480. ),
  1481. )
  1482. class GitCredentialStoreTests(TestCase):
  1483. @classmethod
  1484. def setUpClass(cls):
  1485. with tempfile.NamedTemporaryFile(delete=False) as f:
  1486. f.write(b"https://user:pass@example.org\n")
  1487. cls.fname = f.name
  1488. @classmethod
  1489. def tearDownClass(cls):
  1490. os.unlink(cls.fname)
  1491. def test_nonmatching_scheme(self):
  1492. self.assertEqual(
  1493. get_credentials_from_store(b"http", b"example.org", fnames=[self.fname]),
  1494. None,
  1495. )
  1496. def test_nonmatching_hostname(self):
  1497. self.assertEqual(
  1498. get_credentials_from_store(b"https", b"noentry.org", fnames=[self.fname]),
  1499. None,
  1500. )
  1501. def test_match_without_username(self):
  1502. self.assertEqual(
  1503. get_credentials_from_store(b"https", b"example.org", fnames=[self.fname]),
  1504. (b"user", b"pass"),
  1505. )
  1506. def test_match_with_matching_username(self):
  1507. self.assertEqual(
  1508. get_credentials_from_store(
  1509. b"https", b"example.org", b"user", fnames=[self.fname]
  1510. ),
  1511. (b"user", b"pass"),
  1512. )
  1513. def test_no_match_with_nonmatching_username(self):
  1514. self.assertEqual(
  1515. get_credentials_from_store(
  1516. b"https", b"example.org", b"otheruser", fnames=[self.fname]
  1517. ),
  1518. None,
  1519. )
  1520. class RemoteErrorFromStderrTests(TestCase):
  1521. def test_nothing(self):
  1522. self.assertEqual(_remote_error_from_stderr(None), HangupException())
  1523. def test_error_line(self):
  1524. b = BytesIO(
  1525. b"""\
  1526. This is some random output.
  1527. ERROR: This is the actual error
  1528. with a tail
  1529. """
  1530. )
  1531. self.assertEqual(
  1532. _remote_error_from_stderr(b),
  1533. GitProtocolError("This is the actual error"),
  1534. )
  1535. def test_no_error_line(self):
  1536. b = BytesIO(
  1537. b"""\
  1538. This is output without an error line.
  1539. And this line is just random noise, too.
  1540. """
  1541. )
  1542. self.assertEqual(
  1543. _remote_error_from_stderr(b),
  1544. HangupException(
  1545. [
  1546. b"This is output without an error line.",
  1547. b"And this line is just random noise, too.",
  1548. ]
  1549. ),
  1550. )