test_client.py 55 KB

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