test_client.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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 sys
  23. import shutil
  24. import tempfile
  25. import warnings
  26. try:
  27. from urllib import quote as urlquote
  28. except ImportError:
  29. from urllib.parse import quote as urlquote
  30. try:
  31. import urlparse
  32. except ImportError:
  33. import urllib.parse as urlparse
  34. import urllib3
  35. import dulwich
  36. from dulwich import (
  37. client,
  38. )
  39. from dulwich.client import (
  40. InvalidWants,
  41. LocalGitClient,
  42. TraditionalGitClient,
  43. TCPGitClient,
  44. SSHGitClient,
  45. HttpGitClient,
  46. FetchPackResult,
  47. ReportStatusParser,
  48. SendPackError,
  49. StrangeHostname,
  50. SubprocessSSHVendor,
  51. PLinkSSHVendor,
  52. UpdateRefsError,
  53. check_wants,
  54. default_urllib3_manager,
  55. get_transport_and_path,
  56. get_transport_and_path_from_url,
  57. parse_rsync_url,
  58. )
  59. from dulwich.config import (
  60. ConfigDict,
  61. )
  62. from dulwich.tests import (
  63. TestCase,
  64. )
  65. from dulwich.protocol import (
  66. TCP_GIT_PORT,
  67. Protocol,
  68. )
  69. from dulwich.pack import (
  70. pack_objects_to_data,
  71. write_pack_data,
  72. write_pack_objects,
  73. )
  74. from dulwich.objects import (
  75. Commit,
  76. Tree
  77. )
  78. from dulwich.repo import (
  79. MemoryRepo,
  80. Repo,
  81. )
  82. from dulwich.tests import skipIf
  83. from dulwich.tests.utils import (
  84. open_repo,
  85. tear_down_repo,
  86. setup_warning_catcher,
  87. )
  88. class DummyClient(TraditionalGitClient):
  89. def __init__(self, can_read, read, write):
  90. self.can_read = can_read
  91. self.read = read
  92. self.write = write
  93. TraditionalGitClient.__init__(self)
  94. def _connect(self, service, path):
  95. return Protocol(self.read, self.write), self.can_read, None
  96. class DummyPopen():
  97. def __init__(self, *args, **kwards):
  98. self.stdin = BytesIO(b"stdin")
  99. self.stdout = BytesIO(b"stdout")
  100. self.stderr = BytesIO(b"stderr")
  101. self.returncode = 0
  102. self.args = args
  103. self.kwargs = kwards
  104. def communicate(self, *args, **kwards):
  105. return ('Running', '')
  106. def wait(self, *args, **kwards):
  107. return False
  108. # TODO(durin42): add unit-level tests of GitClient
  109. class GitClientTests(TestCase):
  110. def setUp(self):
  111. super(GitClientTests, self).setUp()
  112. self.rout = BytesIO()
  113. self.rin = BytesIO()
  114. self.client = DummyClient(lambda x: True, self.rin.read,
  115. self.rout.write)
  116. def test_caps(self):
  117. agent_cap = (
  118. 'agent=dulwich/%d.%d.%d' % dulwich.__version__).encode('ascii')
  119. self.assertEqual(set([b'multi_ack', b'side-band-64k', b'ofs-delta',
  120. b'thin-pack', b'multi_ack_detailed', b'shallow',
  121. agent_cap]),
  122. set(self.client._fetch_capabilities))
  123. self.assertEqual(
  124. set([b'delete-refs', b'ofs-delta', b'report-status',
  125. b'side-band-64k', agent_cap]),
  126. set(self.client._send_capabilities))
  127. def test_archive_ack(self):
  128. self.rin.write(
  129. b'0009NACK\n'
  130. b'0000')
  131. self.rin.seek(0)
  132. self.client.archive(b'bla', b'HEAD', None, None)
  133. self.assertEqual(self.rout.getvalue(), b'0011argument HEAD0000')
  134. def test_fetch_empty(self):
  135. self.rin.write(b'0000')
  136. self.rin.seek(0)
  137. def check_heads(heads):
  138. self.assertEqual(heads, {})
  139. return []
  140. ret = self.client.fetch_pack(b'/', check_heads, None, None)
  141. self.assertEqual({}, ret.refs)
  142. self.assertEqual({}, ret.symrefs)
  143. def test_fetch_pack_ignores_magic_ref(self):
  144. self.rin.write(
  145. b'00000000000000000000000000000000000000000000 capabilities^{}'
  146. b'\x00 multi_ack '
  147. b'thin-pack side-band side-band-64k ofs-delta shallow no-progress '
  148. b'include-tag\n'
  149. b'0000')
  150. self.rin.seek(0)
  151. def check_heads(heads):
  152. self.assertEqual({}, heads)
  153. return []
  154. ret = self.client.fetch_pack(b'bla', check_heads, None, None, None)
  155. self.assertEqual({}, ret.refs)
  156. self.assertEqual({}, ret.symrefs)
  157. self.assertEqual(self.rout.getvalue(), b'0000')
  158. def test_fetch_pack_none(self):
  159. self.rin.write(
  160. b'008855dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 HEAD\x00multi_ack '
  161. b'thin-pack side-band side-band-64k ofs-delta shallow no-progress '
  162. b'include-tag\n'
  163. b'0000')
  164. self.rin.seek(0)
  165. ret = self.client.fetch_pack(
  166. b'bla', lambda heads: [], None, None, None)
  167. self.assertEqual(
  168. {b'HEAD': b'55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7'},
  169. ret.refs)
  170. self.assertEqual({}, ret.symrefs)
  171. self.assertEqual(self.rout.getvalue(), b'0000')
  172. def test_send_pack_no_sideband64k_with_update_ref_error(self):
  173. # No side-bank-64k reported by server shouldn't try to parse
  174. # side band data
  175. pkts = [b'55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}'
  176. b'\x00 report-status delete-refs ofs-delta\n',
  177. b'',
  178. b"unpack ok",
  179. b"ng refs/foo/bar pre-receive hook declined",
  180. b'']
  181. for pkt in pkts:
  182. if pkt == b'':
  183. self.rin.write(b"0000")
  184. else:
  185. self.rin.write(("%04x" % (len(pkt)+4)).encode('ascii') + pkt)
  186. self.rin.seek(0)
  187. tree = Tree()
  188. commit = Commit()
  189. commit.tree = tree
  190. commit.parents = []
  191. commit.author = commit.committer = b'test user'
  192. commit.commit_time = commit.author_time = 1174773719
  193. commit.commit_timezone = commit.author_timezone = 0
  194. commit.encoding = b'UTF-8'
  195. commit.message = b'test message'
  196. def update_refs(refs):
  197. return {b'refs/foo/bar': commit.id, }
  198. def generate_pack_data(have, want, ofs_delta=False):
  199. return pack_objects_to_data([(commit, None), (tree, ''), ])
  200. self.assertRaises(UpdateRefsError,
  201. self.client.send_pack, "blah",
  202. update_refs, generate_pack_data)
  203. def test_send_pack_none(self):
  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. self.rin.seek(0)
  210. def update_refs(refs):
  211. return {
  212. b'refs/heads/master':
  213. b'310ca9477129b8586fa2afc779c1f57cf64bba6c'
  214. }
  215. def generate_pack_data(have, want, ofs_delta=False):
  216. return 0, []
  217. self.client.send_pack(b'/', update_refs, set(), generate_pack_data)
  218. self.assertEqual(self.rout.getvalue(), b'0000')
  219. def test_send_pack_keep_and_delete(self):
  220. self.rin.write(
  221. b'0063310ca9477129b8586fa2afc779c1f57cf64bba6c '
  222. b'refs/heads/master\x00report-status delete-refs ofs-delta\n'
  223. b'003f310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/keepme\n'
  224. b'0000000eunpack ok\n'
  225. b'0019ok refs/heads/master\n'
  226. b'0000')
  227. self.rin.seek(0)
  228. def update_refs(refs):
  229. return {b'refs/heads/master': b'0' * 40}
  230. def generate_pack_data(have, want, ofs_delta=False):
  231. return 0, []
  232. self.client.send_pack(b'/', update_refs, generate_pack_data)
  233. self.assertEqual(
  234. self.rout.getvalue(),
  235. b'008b310ca9477129b8586fa2afc779c1f57cf64bba6c '
  236. b'0000000000000000000000000000000000000000 '
  237. b'refs/heads/master\x00delete-refs ofs-delta report-status0000')
  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. self.rin.seek(0)
  246. def update_refs(refs):
  247. return {b'refs/heads/master': b'0' * 40}
  248. def generate_pack_data(have, want, ofs_delta=False):
  249. return 0, []
  250. self.client.send_pack(b'/', update_refs, generate_pack_data)
  251. self.assertEqual(
  252. self.rout.getvalue(),
  253. b'008b310ca9477129b8586fa2afc779c1f57cf64bba6c '
  254. b'0000000000000000000000000000000000000000 '
  255. b'refs/heads/master\x00delete-refs ofs-delta report-status0000')
  256. def test_send_pack_new_ref_only(self):
  257. self.rin.write(
  258. b'0063310ca9477129b8586fa2afc779c1f57cf64bba6c '
  259. b'refs/heads/master\x00report-status delete-refs ofs-delta\n'
  260. b'0000000eunpack ok\n'
  261. b'0019ok refs/heads/blah12\n'
  262. b'0000')
  263. self.rin.seek(0)
  264. def update_refs(refs):
  265. return {
  266. b'refs/heads/blah12':
  267. b'310ca9477129b8586fa2afc779c1f57cf64bba6c',
  268. b'refs/heads/master':
  269. b'310ca9477129b8586fa2afc779c1f57cf64bba6c'
  270. }
  271. def generate_pack_data(have, want, ofs_delta=False):
  272. return 0, []
  273. f = BytesIO()
  274. write_pack_objects(f, {})
  275. self.client.send_pack('/', update_refs, generate_pack_data)
  276. self.assertEqual(
  277. self.rout.getvalue(),
  278. b'008b0000000000000000000000000000000000000000 '
  279. b'310ca9477129b8586fa2afc779c1f57cf64bba6c '
  280. b'refs/heads/blah12\x00delete-refs ofs-delta report-status0000' +
  281. f.getvalue())
  282. def test_send_pack_new_ref(self):
  283. self.rin.write(
  284. b'0064310ca9477129b8586fa2afc779c1f57cf64bba6c '
  285. b'refs/heads/master\x00 report-status delete-refs ofs-delta\n'
  286. b'0000000eunpack ok\n'
  287. b'0019ok refs/heads/blah12\n'
  288. b'0000')
  289. self.rin.seek(0)
  290. tree = Tree()
  291. commit = Commit()
  292. commit.tree = tree
  293. commit.parents = []
  294. commit.author = commit.committer = b'test user'
  295. commit.commit_time = commit.author_time = 1174773719
  296. commit.commit_timezone = commit.author_timezone = 0
  297. commit.encoding = b'UTF-8'
  298. commit.message = b'test message'
  299. def update_refs(refs):
  300. return {
  301. b'refs/heads/blah12': commit.id,
  302. b'refs/heads/master':
  303. b'310ca9477129b8586fa2afc779c1f57cf64bba6c'
  304. }
  305. def generate_pack_data(have, want, ofs_delta=False):
  306. return pack_objects_to_data([(commit, None), (tree, b''), ])
  307. f = BytesIO()
  308. write_pack_data(f, *generate_pack_data(None, None))
  309. self.client.send_pack(b'/', update_refs, generate_pack_data)
  310. self.assertEqual(
  311. self.rout.getvalue(),
  312. b'008b0000000000000000000000000000000000000000 ' + commit.id +
  313. b' refs/heads/blah12\x00delete-refs ofs-delta report-status0000' +
  314. f.getvalue())
  315. def test_send_pack_no_deleteref_delete_only(self):
  316. pkts = [b'310ca9477129b8586fa2afc779c1f57cf64bba6c refs/heads/master'
  317. b'\x00 report-status ofs-delta\n',
  318. b'',
  319. b'']
  320. for pkt in pkts:
  321. if pkt == b'':
  322. self.rin.write(b"0000")
  323. else:
  324. self.rin.write(("%04x" % (len(pkt)+4)).encode('ascii') + pkt)
  325. self.rin.seek(0)
  326. def update_refs(refs):
  327. return {b'refs/heads/master': b'0' * 40}
  328. def generate_pack_data(have, want, ofs_delta=False):
  329. return 0, []
  330. self.assertRaises(UpdateRefsError,
  331. self.client.send_pack, b"/",
  332. update_refs, generate_pack_data)
  333. self.assertEqual(self.rout.getvalue(), b'0000')
  334. class TestGetTransportAndPath(TestCase):
  335. def test_tcp(self):
  336. c, path = get_transport_and_path('git://foo.com/bar/baz')
  337. self.assertTrue(isinstance(c, TCPGitClient))
  338. self.assertEqual('foo.com', c._host)
  339. self.assertEqual(TCP_GIT_PORT, c._port)
  340. self.assertEqual('/bar/baz', path)
  341. def test_tcp_port(self):
  342. c, path = get_transport_and_path('git://foo.com:1234/bar/baz')
  343. self.assertTrue(isinstance(c, TCPGitClient))
  344. self.assertEqual('foo.com', c._host)
  345. self.assertEqual(1234, c._port)
  346. self.assertEqual('/bar/baz', path)
  347. def test_git_ssh_explicit(self):
  348. c, path = get_transport_and_path('git+ssh://foo.com/bar/baz')
  349. self.assertTrue(isinstance(c, SSHGitClient))
  350. self.assertEqual('foo.com', c.host)
  351. self.assertEqual(None, c.port)
  352. self.assertEqual(None, c.username)
  353. self.assertEqual('/bar/baz', path)
  354. def test_ssh_explicit(self):
  355. c, path = get_transport_and_path('ssh://foo.com/bar/baz')
  356. self.assertTrue(isinstance(c, SSHGitClient))
  357. self.assertEqual('foo.com', c.host)
  358. self.assertEqual(None, c.port)
  359. self.assertEqual(None, c.username)
  360. self.assertEqual('/bar/baz', path)
  361. def test_ssh_port_explicit(self):
  362. c, path = get_transport_and_path(
  363. 'git+ssh://foo.com:1234/bar/baz')
  364. self.assertTrue(isinstance(c, SSHGitClient))
  365. self.assertEqual('foo.com', c.host)
  366. self.assertEqual(1234, c.port)
  367. self.assertEqual('/bar/baz', path)
  368. def test_username_and_port_explicit_unknown_scheme(self):
  369. c, path = get_transport_and_path(
  370. 'unknown://git@server:7999/dply/stuff.git')
  371. self.assertTrue(isinstance(c, SSHGitClient))
  372. self.assertEqual('unknown', c.host)
  373. self.assertEqual('//git@server:7999/dply/stuff.git', path)
  374. def test_username_and_port_explicit(self):
  375. c, path = get_transport_and_path(
  376. 'ssh://git@server:7999/dply/stuff.git')
  377. self.assertTrue(isinstance(c, SSHGitClient))
  378. self.assertEqual('git', c.username)
  379. self.assertEqual('server', c.host)
  380. self.assertEqual(7999, c.port)
  381. self.assertEqual('/dply/stuff.git', path)
  382. def test_ssh_abspath_doubleslash(self):
  383. c, path = get_transport_and_path('git+ssh://foo.com//bar/baz')
  384. self.assertTrue(isinstance(c, SSHGitClient))
  385. self.assertEqual('foo.com', c.host)
  386. self.assertEqual(None, c.port)
  387. self.assertEqual(None, c.username)
  388. self.assertEqual('//bar/baz', path)
  389. def test_ssh_port(self):
  390. c, path = get_transport_and_path(
  391. 'git+ssh://foo.com:1234/bar/baz')
  392. self.assertTrue(isinstance(c, SSHGitClient))
  393. self.assertEqual('foo.com', c.host)
  394. self.assertEqual(1234, c.port)
  395. self.assertEqual('/bar/baz', path)
  396. def test_ssh_implicit(self):
  397. c, path = get_transport_and_path('foo:/bar/baz')
  398. self.assertTrue(isinstance(c, SSHGitClient))
  399. self.assertEqual('foo', c.host)
  400. self.assertEqual(None, c.port)
  401. self.assertEqual(None, c.username)
  402. self.assertEqual('/bar/baz', path)
  403. def test_ssh_host(self):
  404. c, path = get_transport_and_path('foo.com:/bar/baz')
  405. self.assertTrue(isinstance(c, SSHGitClient))
  406. self.assertEqual('foo.com', c.host)
  407. self.assertEqual(None, c.port)
  408. self.assertEqual(None, c.username)
  409. self.assertEqual('/bar/baz', path)
  410. def test_ssh_user_host(self):
  411. c, path = get_transport_and_path('user@foo.com:/bar/baz')
  412. self.assertTrue(isinstance(c, SSHGitClient))
  413. self.assertEqual('foo.com', c.host)
  414. self.assertEqual(None, c.port)
  415. self.assertEqual('user', c.username)
  416. self.assertEqual('/bar/baz', path)
  417. def test_ssh_relpath(self):
  418. c, path = get_transport_and_path('foo:bar/baz')
  419. self.assertTrue(isinstance(c, SSHGitClient))
  420. self.assertEqual('foo', c.host)
  421. self.assertEqual(None, c.port)
  422. self.assertEqual(None, c.username)
  423. self.assertEqual('bar/baz', path)
  424. def test_ssh_host_relpath(self):
  425. c, path = get_transport_and_path('foo.com:bar/baz')
  426. self.assertTrue(isinstance(c, SSHGitClient))
  427. self.assertEqual('foo.com', c.host)
  428. self.assertEqual(None, c.port)
  429. self.assertEqual(None, c.username)
  430. self.assertEqual('bar/baz', path)
  431. def test_ssh_user_host_relpath(self):
  432. c, path = get_transport_and_path('user@foo.com:bar/baz')
  433. self.assertTrue(isinstance(c, SSHGitClient))
  434. self.assertEqual('foo.com', c.host)
  435. self.assertEqual(None, c.port)
  436. self.assertEqual('user', c.username)
  437. self.assertEqual('bar/baz', path)
  438. def test_local(self):
  439. c, path = get_transport_and_path('foo.bar/baz')
  440. self.assertTrue(isinstance(c, LocalGitClient))
  441. self.assertEqual('foo.bar/baz', path)
  442. @skipIf(sys.platform != 'win32', 'Behaviour only happens on windows.')
  443. def test_local_abs_windows_path(self):
  444. c, path = get_transport_and_path('C:\\foo.bar\\baz')
  445. self.assertTrue(isinstance(c, LocalGitClient))
  446. self.assertEqual('C:\\foo.bar\\baz', path)
  447. def test_error(self):
  448. # Need to use a known urlparse.uses_netloc URL scheme to get the
  449. # expected parsing of the URL on Python versions less than 2.6.5
  450. c, path = get_transport_and_path('prospero://bar/baz')
  451. self.assertTrue(isinstance(c, SSHGitClient))
  452. def test_http(self):
  453. url = 'https://github.com/jelmer/dulwich'
  454. c, path = get_transport_and_path(url)
  455. self.assertTrue(isinstance(c, HttpGitClient))
  456. self.assertEqual('/jelmer/dulwich', path)
  457. def test_http_auth(self):
  458. url = 'https://user:passwd@github.com/jelmer/dulwich'
  459. c, path = get_transport_and_path(url)
  460. self.assertTrue(isinstance(c, HttpGitClient))
  461. self.assertEqual('/jelmer/dulwich', path)
  462. self.assertEqual('user', c._username)
  463. self.assertEqual('passwd', c._password)
  464. def test_http_auth_with_username(self):
  465. url = 'https://github.com/jelmer/dulwich'
  466. c, path = get_transport_and_path(
  467. url, username='user2', password='blah')
  468. self.assertTrue(isinstance(c, HttpGitClient))
  469. self.assertEqual('/jelmer/dulwich', path)
  470. self.assertEqual('user2', c._username)
  471. self.assertEqual('blah', c._password)
  472. def test_http_auth_with_username_and_in_url(self):
  473. url = 'https://user:passwd@github.com/jelmer/dulwich'
  474. c, path = get_transport_and_path(
  475. url, username='user2', password='blah')
  476. self.assertTrue(isinstance(c, HttpGitClient))
  477. self.assertEqual('/jelmer/dulwich', path)
  478. self.assertEqual('user', c._username)
  479. self.assertEqual('passwd', c._password)
  480. def test_http_no_auth(self):
  481. url = 'https://github.com/jelmer/dulwich'
  482. c, path = get_transport_and_path(url)
  483. self.assertTrue(isinstance(c, HttpGitClient))
  484. self.assertEqual('/jelmer/dulwich', path)
  485. self.assertIs(None, c._username)
  486. self.assertIs(None, c._password)
  487. class TestGetTransportAndPathFromUrl(TestCase):
  488. def test_tcp(self):
  489. c, path = get_transport_and_path_from_url('git://foo.com/bar/baz')
  490. self.assertTrue(isinstance(c, TCPGitClient))
  491. self.assertEqual('foo.com', c._host)
  492. self.assertEqual(TCP_GIT_PORT, c._port)
  493. self.assertEqual('/bar/baz', path)
  494. def test_tcp_port(self):
  495. c, path = get_transport_and_path_from_url('git://foo.com:1234/bar/baz')
  496. self.assertTrue(isinstance(c, TCPGitClient))
  497. self.assertEqual('foo.com', c._host)
  498. self.assertEqual(1234, c._port)
  499. self.assertEqual('/bar/baz', path)
  500. def test_ssh_explicit(self):
  501. c, path = get_transport_and_path_from_url('git+ssh://foo.com/bar/baz')
  502. self.assertTrue(isinstance(c, SSHGitClient))
  503. self.assertEqual('foo.com', c.host)
  504. self.assertEqual(None, c.port)
  505. self.assertEqual(None, c.username)
  506. self.assertEqual('/bar/baz', path)
  507. def test_ssh_port_explicit(self):
  508. c, path = get_transport_and_path_from_url(
  509. 'git+ssh://foo.com:1234/bar/baz')
  510. self.assertTrue(isinstance(c, SSHGitClient))
  511. self.assertEqual('foo.com', c.host)
  512. self.assertEqual(1234, c.port)
  513. self.assertEqual('/bar/baz', path)
  514. def test_ssh_homepath(self):
  515. c, path = get_transport_and_path_from_url(
  516. 'git+ssh://foo.com/~/bar/baz')
  517. self.assertTrue(isinstance(c, SSHGitClient))
  518. self.assertEqual('foo.com', c.host)
  519. self.assertEqual(None, c.port)
  520. self.assertEqual(None, c.username)
  521. self.assertEqual('/~/bar/baz', path)
  522. def test_ssh_port_homepath(self):
  523. c, path = get_transport_and_path_from_url(
  524. 'git+ssh://foo.com:1234/~/bar/baz')
  525. self.assertTrue(isinstance(c, SSHGitClient))
  526. self.assertEqual('foo.com', c.host)
  527. self.assertEqual(1234, c.port)
  528. self.assertEqual('/~/bar/baz', path)
  529. def test_ssh_host_relpath(self):
  530. self.assertRaises(
  531. ValueError, get_transport_and_path_from_url,
  532. 'foo.com:bar/baz')
  533. def test_ssh_user_host_relpath(self):
  534. self.assertRaises(
  535. ValueError, get_transport_and_path_from_url,
  536. 'user@foo.com:bar/baz')
  537. def test_local_path(self):
  538. self.assertRaises(
  539. ValueError, get_transport_and_path_from_url,
  540. 'foo.bar/baz')
  541. def test_error(self):
  542. # Need to use a known urlparse.uses_netloc URL scheme to get the
  543. # expected parsing of the URL on Python versions less than 2.6.5
  544. self.assertRaises(
  545. ValueError, get_transport_and_path_from_url,
  546. 'prospero://bar/baz')
  547. def test_http(self):
  548. url = 'https://github.com/jelmer/dulwich'
  549. c, path = get_transport_and_path_from_url(url)
  550. self.assertTrue(isinstance(c, HttpGitClient))
  551. self.assertEqual('https://github.com', c.get_url(b'/'))
  552. self.assertEqual('/jelmer/dulwich', path)
  553. def test_http_port(self):
  554. url = 'https://github.com:9090/jelmer/dulwich'
  555. c, path = get_transport_and_path_from_url(url)
  556. self.assertEqual('https://github.com:9090', c.get_url(b'/'))
  557. self.assertTrue(isinstance(c, HttpGitClient))
  558. self.assertEqual('/jelmer/dulwich', path)
  559. def test_file(self):
  560. c, path = get_transport_and_path_from_url('file:///home/jelmer/foo')
  561. self.assertTrue(isinstance(c, LocalGitClient))
  562. self.assertEqual('/home/jelmer/foo', path)
  563. class TestSSHVendor(object):
  564. def __init__(self):
  565. self.host = None
  566. self.command = ""
  567. self.username = None
  568. self.port = None
  569. self.password = None
  570. self.key_filename = None
  571. def run_command(self, host, command, username=None, port=None,
  572. password=None, key_filename=None):
  573. self.host = host
  574. self.command = command
  575. self.username = username
  576. self.port = port
  577. self.password = password
  578. self.key_filename = key_filename
  579. class Subprocess:
  580. pass
  581. setattr(Subprocess, 'read', lambda: None)
  582. setattr(Subprocess, 'write', lambda: None)
  583. setattr(Subprocess, 'close', lambda: None)
  584. setattr(Subprocess, 'can_read', lambda: None)
  585. return Subprocess()
  586. class SSHGitClientTests(TestCase):
  587. def setUp(self):
  588. super(SSHGitClientTests, self).setUp()
  589. self.server = TestSSHVendor()
  590. self.real_vendor = client.get_ssh_vendor
  591. client.get_ssh_vendor = lambda: self.server
  592. self.client = SSHGitClient('git.samba.org')
  593. def tearDown(self):
  594. super(SSHGitClientTests, self).tearDown()
  595. client.get_ssh_vendor = self.real_vendor
  596. def test_get_url(self):
  597. path = '/tmp/repo.git'
  598. c = SSHGitClient('git.samba.org')
  599. url = c.get_url(path)
  600. self.assertEqual('ssh://git.samba.org/tmp/repo.git', url)
  601. def test_get_url_with_username_and_port(self):
  602. path = '/tmp/repo.git'
  603. c = SSHGitClient('git.samba.org', port=2222, username='user')
  604. url = c.get_url(path)
  605. self.assertEqual('ssh://user@git.samba.org:2222/tmp/repo.git', url)
  606. def test_default_command(self):
  607. self.assertEqual(
  608. b'git-upload-pack',
  609. self.client._get_cmd_path(b'upload-pack'))
  610. def test_alternative_command_path(self):
  611. self.client.alternative_paths[b'upload-pack'] = (
  612. b'/usr/lib/git/git-upload-pack')
  613. self.assertEqual(
  614. b'/usr/lib/git/git-upload-pack',
  615. self.client._get_cmd_path(b'upload-pack'))
  616. def test_alternative_command_path_spaces(self):
  617. self.client.alternative_paths[b'upload-pack'] = (
  618. b'/usr/lib/git/git-upload-pack -ibla')
  619. self.assertEqual(b"/usr/lib/git/git-upload-pack -ibla",
  620. self.client._get_cmd_path(b'upload-pack'))
  621. def test_connect(self):
  622. server = self.server
  623. client = self.client
  624. client.username = b"username"
  625. client.port = 1337
  626. client._connect(b"command", b"/path/to/repo")
  627. self.assertEqual(b"username", server.username)
  628. self.assertEqual(1337, server.port)
  629. self.assertEqual("git-command '/path/to/repo'", server.command)
  630. client._connect(b"relative-command", b"/~/path/to/repo")
  631. self.assertEqual("git-relative-command '~/path/to/repo'",
  632. server.command)
  633. class ReportStatusParserTests(TestCase):
  634. def test_invalid_pack(self):
  635. parser = ReportStatusParser()
  636. parser.handle_packet(b"unpack error - foo bar")
  637. parser.handle_packet(b"ok refs/foo/bar")
  638. parser.handle_packet(None)
  639. self.assertRaises(SendPackError, parser.check)
  640. def test_update_refs_error(self):
  641. parser = ReportStatusParser()
  642. parser.handle_packet(b"unpack ok")
  643. parser.handle_packet(b"ng refs/foo/bar need to pull")
  644. parser.handle_packet(None)
  645. self.assertRaises(UpdateRefsError, parser.check)
  646. def test_ok(self):
  647. parser = ReportStatusParser()
  648. parser.handle_packet(b"unpack ok")
  649. parser.handle_packet(b"ok refs/foo/bar")
  650. parser.handle_packet(None)
  651. parser.check()
  652. class LocalGitClientTests(TestCase):
  653. def test_get_url(self):
  654. path = "/tmp/repo.git"
  655. c = LocalGitClient()
  656. url = c.get_url(path)
  657. self.assertEqual('file:///tmp/repo.git', url)
  658. def test_fetch_into_empty(self):
  659. c = LocalGitClient()
  660. t = MemoryRepo()
  661. s = open_repo('a.git')
  662. self.addCleanup(tear_down_repo, s)
  663. self.assertEqual(s.get_refs(), c.fetch(s.path, t).refs)
  664. def test_fetch_empty(self):
  665. c = LocalGitClient()
  666. s = open_repo('a.git')
  667. self.addCleanup(tear_down_repo, s)
  668. out = BytesIO()
  669. walker = {}
  670. ret = c.fetch_pack(
  671. s.path, lambda heads: [], graph_walker=walker, pack_data=out.write)
  672. self.assertEqual({
  673. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  674. b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  675. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  676. b'refs/tags/mytag-packed':
  677. b'b0931cadc54336e78a1d980420e3268903b57a50'
  678. }, ret.refs)
  679. self.assertEqual(
  680. {b'HEAD': b'refs/heads/master'},
  681. ret.symrefs)
  682. self.assertEqual(
  683. b"PACK\x00\x00\x00\x02\x00\x00\x00\x00\x02\x9d\x08"
  684. b"\x82;\xd8\xa8\xea\xb5\x10\xadj\xc7\\\x82<\xfd>\xd3\x1e",
  685. out.getvalue())
  686. def test_fetch_pack_none(self):
  687. c = LocalGitClient()
  688. s = open_repo('a.git')
  689. self.addCleanup(tear_down_repo, s)
  690. out = BytesIO()
  691. walker = MemoryRepo().get_graph_walker()
  692. ret = c.fetch_pack(
  693. s.path,
  694. lambda heads: [b"a90fa2d900a17e99b433217e988c4eb4a2e9a097"],
  695. graph_walker=walker, pack_data=out.write)
  696. self.assertEqual({b'HEAD': b'refs/heads/master'}, ret.symrefs)
  697. self.assertEqual({
  698. b'HEAD': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  699. b'refs/heads/master': b'a90fa2d900a17e99b433217e988c4eb4a2e9a097',
  700. b'refs/tags/mytag': b'28237f4dc30d0d462658d6b937b08a0f0b6ef55a',
  701. b'refs/tags/mytag-packed':
  702. b'b0931cadc54336e78a1d980420e3268903b57a50'
  703. }, ret.refs)
  704. # Hardcoding is not ideal, but we'll fix that some other day..
  705. self.assertTrue(out.getvalue().startswith(
  706. b'PACK\x00\x00\x00\x02\x00\x00\x00\x07'))
  707. def test_send_pack_without_changes(self):
  708. local = open_repo('a.git')
  709. self.addCleanup(tear_down_repo, local)
  710. target = open_repo('a.git')
  711. self.addCleanup(tear_down_repo, target)
  712. self.send_and_verify(b"master", local, target)
  713. def test_send_pack_with_changes(self):
  714. local = open_repo('a.git')
  715. self.addCleanup(tear_down_repo, local)
  716. target_path = tempfile.mkdtemp()
  717. self.addCleanup(shutil.rmtree, target_path)
  718. with Repo.init_bare(target_path) as target:
  719. self.send_and_verify(b"master", local, target)
  720. def test_get_refs(self):
  721. local = open_repo('refs.git')
  722. self.addCleanup(tear_down_repo, local)
  723. client = LocalGitClient()
  724. refs = client.get_refs(local.path)
  725. self.assertDictEqual(local.refs.as_dict(), refs)
  726. def send_and_verify(self, branch, local, target):
  727. """Send branch from local to remote repository and verify it worked."""
  728. client = LocalGitClient()
  729. ref_name = b"refs/heads/" + branch
  730. new_refs = client.send_pack(target.path,
  731. lambda _: {ref_name: local.refs[ref_name]},
  732. local.generate_pack_data)
  733. self.assertEqual(local.refs[ref_name], new_refs[ref_name])
  734. obj_local = local.get_object(new_refs[ref_name])
  735. obj_target = target.get_object(new_refs[ref_name])
  736. self.assertEqual(obj_local, obj_target)
  737. class HttpGitClientTests(TestCase):
  738. @staticmethod
  739. def b64encode(s):
  740. """Python 2/3 compatible Base64 encoder. Returns string."""
  741. try:
  742. return base64.b64encode(s)
  743. except TypeError:
  744. return base64.b64encode(s.encode('latin1')).decode('ascii')
  745. def test_get_url(self):
  746. base_url = 'https://github.com/jelmer/dulwich'
  747. path = '/jelmer/dulwich'
  748. c = HttpGitClient(base_url)
  749. url = c.get_url(path)
  750. self.assertEqual('https://github.com/jelmer/dulwich', url)
  751. def test_get_url_bytes_path(self):
  752. base_url = 'https://github.com/jelmer/dulwich'
  753. path_bytes = b'/jelmer/dulwich'
  754. c = HttpGitClient(base_url)
  755. url = c.get_url(path_bytes)
  756. self.assertEqual('https://github.com/jelmer/dulwich', url)
  757. def test_get_url_with_username_and_passwd(self):
  758. base_url = 'https://github.com/jelmer/dulwich'
  759. path = '/jelmer/dulwich'
  760. c = HttpGitClient(base_url, username='USERNAME', password='PASSWD')
  761. url = c.get_url(path)
  762. self.assertEqual('https://github.com/jelmer/dulwich', url)
  763. def test_init_username_passwd_set(self):
  764. url = 'https://github.com/jelmer/dulwich'
  765. c = HttpGitClient(url, config=None, username='user', password='passwd')
  766. self.assertEqual('user', c._username)
  767. self.assertEqual('passwd', c._password)
  768. basic_auth = c.pool_manager.headers['authorization']
  769. auth_string = '%s:%s' % ('user', 'passwd')
  770. b64_credentials = self.b64encode(auth_string)
  771. expected_basic_auth = 'Basic %s' % b64_credentials
  772. self.assertEqual(basic_auth, expected_basic_auth)
  773. def test_init_no_username_passwd(self):
  774. url = 'https://github.com/jelmer/dulwich'
  775. c = HttpGitClient(url, config=None)
  776. self.assertIs(None, c._username)
  777. self.assertIs(None, c._password)
  778. self.assertNotIn('authorization', c.pool_manager.headers)
  779. def test_from_parsedurl_on_url_with_quoted_credentials(self):
  780. original_username = 'john|the|first'
  781. quoted_username = urlquote(original_username)
  782. original_password = 'Ya#1$2%3'
  783. quoted_password = urlquote(original_password)
  784. url = 'https://{username}:{password}@github.com/jelmer/dulwich'.format(
  785. username=quoted_username,
  786. password=quoted_password
  787. )
  788. c = HttpGitClient.from_parsedurl(urlparse.urlparse(url))
  789. self.assertEqual(original_username, c._username)
  790. self.assertEqual(original_password, c._password)
  791. basic_auth = c.pool_manager.headers['authorization']
  792. auth_string = '%s:%s' % (original_username, original_password)
  793. b64_credentials = self.b64encode(auth_string)
  794. expected_basic_auth = 'Basic %s' % str(b64_credentials)
  795. self.assertEqual(basic_auth, expected_basic_auth)
  796. def test_url_redirect_location(self):
  797. from urllib3.response import HTTPResponse
  798. test_data = {
  799. 'https://gitlab.com/inkscape/inkscape/': {
  800. 'redirect_url': 'https://gitlab.com/inkscape/inkscape.git/',
  801. 'refs_data': (b'001e# service=git-upload-pack\n00000032'
  802. b'fb2bebf4919a011f0fd7cec085443d0031228e76 '
  803. b'HEAD\n0000')
  804. },
  805. 'https://github.com/jelmer/dulwich/': {
  806. 'redirect_url': 'https://github.com/jelmer/dulwich/',
  807. 'refs_data': (b'001e# service=git-upload-pack\n00000032'
  808. b'3ff25e09724aa4d86ea5bca7d5dd0399a3c8bfcf '
  809. b'HEAD\n0000')
  810. }
  811. }
  812. tail = 'info/refs?service=git-upload-pack'
  813. # we need to mock urllib3.PoolManager as this test will fail
  814. # otherwise without an active internet connection
  815. class PoolManagerMock():
  816. def __init__(self):
  817. self.headers = {}
  818. def request(self, method, url, fields=None, headers=None,
  819. redirect=True):
  820. base_url = url[:-len(tail)]
  821. redirect_base_url = test_data[base_url]['redirect_url']
  822. redirect_url = redirect_base_url + tail
  823. headers = {
  824. 'Content-Type':
  825. 'application/x-git-upload-pack-advertisement'
  826. }
  827. body = test_data[base_url]['refs_data']
  828. # urllib3 handles automatic redirection by default
  829. status = 200
  830. request_url = redirect_url
  831. # simulate urllib3 behavior when redirect parameter is False
  832. if redirect is False:
  833. request_url = url
  834. if redirect_base_url != base_url:
  835. body = ''
  836. headers['location'] = redirect_url
  837. status = 301
  838. return HTTPResponse(body=body,
  839. headers=headers,
  840. request_method=method,
  841. request_url=request_url,
  842. status=status)
  843. pool_manager = PoolManagerMock()
  844. for base_url in test_data.keys():
  845. # instantiate HttpGitClient with mocked pool manager
  846. c = HttpGitClient(base_url, pool_manager=pool_manager,
  847. config=None)
  848. # call method that detects url redirection
  849. _, _, processed_url = c._discover_references(b'git-upload-pack',
  850. base_url)
  851. # send the same request as the method above without redirection
  852. resp = c.pool_manager.request('GET', base_url + tail,
  853. redirect=False)
  854. # check expected behavior of urllib3
  855. redirect_location = resp.get_redirect_location()
  856. if resp.status == 200:
  857. self.assertFalse(redirect_location)
  858. if redirect_location:
  859. # check that url redirection has been correctly detected
  860. self.assertEqual(processed_url, redirect_location[:-len(tail)])
  861. else:
  862. # check also the no redirection case
  863. self.assertEqual(processed_url, base_url)
  864. class TCPGitClientTests(TestCase):
  865. def test_get_url(self):
  866. host = 'github.com'
  867. path = '/jelmer/dulwich'
  868. c = TCPGitClient(host)
  869. url = c.get_url(path)
  870. self.assertEqual('git://github.com/jelmer/dulwich', url)
  871. def test_get_url_with_port(self):
  872. host = 'github.com'
  873. path = '/jelmer/dulwich'
  874. port = 9090
  875. c = TCPGitClient(host, port=port)
  876. url = c.get_url(path)
  877. self.assertEqual('git://github.com:9090/jelmer/dulwich', url)
  878. class DefaultUrllib3ManagerTest(TestCase):
  879. def test_no_config(self):
  880. manager = default_urllib3_manager(config=None)
  881. self.assertEqual(manager.connection_pool_kw['cert_reqs'],
  882. 'CERT_REQUIRED')
  883. def test_config_no_proxy(self):
  884. manager = default_urllib3_manager(config=ConfigDict())
  885. self.assertNotIsInstance(manager, urllib3.ProxyManager)
  886. def test_config_ssl(self):
  887. config = ConfigDict()
  888. config.set(b'http', b'sslVerify', b'true')
  889. manager = default_urllib3_manager(config=config)
  890. self.assertEqual(manager.connection_pool_kw['cert_reqs'],
  891. 'CERT_REQUIRED')
  892. def test_config_no_ssl(self):
  893. config = ConfigDict()
  894. config.set(b'http', b'sslVerify', b'false')
  895. manager = default_urllib3_manager(config=config)
  896. self.assertEqual(manager.connection_pool_kw['cert_reqs'],
  897. 'CERT_NONE')
  898. def test_config_proxy(self):
  899. config = ConfigDict()
  900. config.set(b'http', b'proxy', b'http://localhost:3128/')
  901. manager = default_urllib3_manager(config=config)
  902. self.assertIsInstance(manager, urllib3.ProxyManager)
  903. self.assertTrue(hasattr(manager, 'proxy'))
  904. self.assertEqual(manager.proxy.scheme, 'http')
  905. self.assertEqual(manager.proxy.host, 'localhost')
  906. self.assertEqual(manager.proxy.port, 3128)
  907. def test_config_no_verify_ssl(self):
  908. manager = default_urllib3_manager(config=None, cert_reqs="CERT_NONE")
  909. self.assertEqual(manager.connection_pool_kw['cert_reqs'], 'CERT_NONE')
  910. class SubprocessSSHVendorTests(TestCase):
  911. def setUp(self):
  912. # Monkey Patch client subprocess popen
  913. self._orig_popen = dulwich.client.subprocess.Popen
  914. dulwich.client.subprocess.Popen = DummyPopen
  915. def tearDown(self):
  916. dulwich.client.subprocess.Popen = self._orig_popen
  917. def test_run_command_dashes(self):
  918. vendor = SubprocessSSHVendor()
  919. self.assertRaises(StrangeHostname, vendor.run_command, '--weird-host',
  920. 'git-clone-url')
  921. def test_run_command_password(self):
  922. vendor = SubprocessSSHVendor()
  923. self.assertRaises(NotImplementedError, vendor.run_command, 'host',
  924. 'git-clone-url', password='12345')
  925. def test_run_command_password_and_privkey(self):
  926. vendor = SubprocessSSHVendor()
  927. self.assertRaises(NotImplementedError, vendor.run_command,
  928. 'host', 'git-clone-url',
  929. password='12345', key_filename='/tmp/id_rsa')
  930. def test_run_command_with_port_username_and_privkey(self):
  931. expected = ['ssh', '-x', '-p', '2200',
  932. '-i', '/tmp/id_rsa', 'user@host', 'git-clone-url']
  933. vendor = SubprocessSSHVendor()
  934. command = vendor.run_command(
  935. 'host', 'git-clone-url',
  936. username='user', port='2200',
  937. key_filename='/tmp/id_rsa')
  938. args = command.proc.args
  939. self.assertListEqual(expected, args[0])
  940. class PLinkSSHVendorTests(TestCase):
  941. def setUp(self):
  942. # Monkey Patch client subprocess popen
  943. self._orig_popen = dulwich.client.subprocess.Popen
  944. dulwich.client.subprocess.Popen = DummyPopen
  945. def tearDown(self):
  946. dulwich.client.subprocess.Popen = self._orig_popen
  947. def test_run_command_dashes(self):
  948. vendor = PLinkSSHVendor()
  949. self.assertRaises(StrangeHostname, vendor.run_command, '--weird-host',
  950. 'git-clone-url')
  951. def test_run_command_password_and_privkey(self):
  952. vendor = PLinkSSHVendor()
  953. warnings.simplefilter("always", UserWarning)
  954. self.addCleanup(warnings.resetwarnings)
  955. warnings_list, restore_warnings = setup_warning_catcher()
  956. self.addCleanup(restore_warnings)
  957. command = vendor.run_command(
  958. 'host', 'git-clone-url', password='12345',
  959. key_filename='/tmp/id_rsa')
  960. expected_warning = UserWarning(
  961. 'Invoking PLink with a password exposes the password in the '
  962. 'process list.')
  963. for w in warnings_list:
  964. if (type(w) == type(expected_warning) and
  965. w.args == expected_warning.args):
  966. break
  967. else:
  968. raise AssertionError(
  969. 'Expected warning %r not in %r' %
  970. (expected_warning, warnings_list))
  971. args = command.proc.args
  972. if sys.platform == 'win32':
  973. binary = ['plink.exe', '-ssh']
  974. else:
  975. binary = ['plink', '-ssh']
  976. expected = binary + [
  977. '-pw', '12345', '-i', '/tmp/id_rsa', 'host', 'git-clone-url']
  978. self.assertListEqual(expected, args[0])
  979. def test_run_command_password(self):
  980. if sys.platform == 'win32':
  981. binary = ['plink.exe', '-ssh']
  982. else:
  983. binary = ['plink', '-ssh']
  984. expected = binary + ['-pw', '12345', 'host', 'git-clone-url']
  985. vendor = PLinkSSHVendor()
  986. warnings.simplefilter("always", UserWarning)
  987. self.addCleanup(warnings.resetwarnings)
  988. warnings_list, restore_warnings = setup_warning_catcher()
  989. self.addCleanup(restore_warnings)
  990. command = vendor.run_command('host', 'git-clone-url', password='12345')
  991. expected_warning = UserWarning(
  992. 'Invoking PLink with a password exposes the password in the '
  993. 'process list.')
  994. for w in warnings_list:
  995. if (type(w) == type(expected_warning) and
  996. w.args == expected_warning.args):
  997. break
  998. else:
  999. raise AssertionError(
  1000. 'Expected warning %r not in %r' %
  1001. (expected_warning, warnings_list))
  1002. args = command.proc.args
  1003. self.assertListEqual(expected, args[0])
  1004. def test_run_command_with_port_username_and_privkey(self):
  1005. if sys.platform == 'win32':
  1006. binary = ['plink.exe', '-ssh']
  1007. else:
  1008. binary = ['plink', '-ssh']
  1009. expected = binary + [
  1010. '-P', '2200', '-i', '/tmp/id_rsa',
  1011. 'user@host', 'git-clone-url']
  1012. vendor = PLinkSSHVendor()
  1013. command = vendor.run_command(
  1014. 'host', 'git-clone-url',
  1015. username='user', port='2200',
  1016. key_filename='/tmp/id_rsa')
  1017. args = command.proc.args
  1018. self.assertListEqual(expected, args[0])
  1019. class RsyncUrlTests(TestCase):
  1020. def test_simple(self):
  1021. self.assertEqual(
  1022. parse_rsync_url('foo:bar/path'),
  1023. (None, 'foo', 'bar/path'))
  1024. self.assertEqual(
  1025. parse_rsync_url('user@foo:bar/path'),
  1026. ('user', 'foo', 'bar/path'))
  1027. def test_path(self):
  1028. self.assertRaises(ValueError, parse_rsync_url, '/path')
  1029. class CheckWantsTests(TestCase):
  1030. def test_fine(self):
  1031. check_wants(
  1032. [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'],
  1033. {b'refs/heads/blah': b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'})
  1034. def test_missing(self):
  1035. self.assertRaises(
  1036. InvalidWants, check_wants,
  1037. [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'],
  1038. {b'refs/heads/blah': b'3f3dc7a53fb752a6961d3a56683df46d4d3bf262'})
  1039. def test_annotated(self):
  1040. self.assertRaises(
  1041. InvalidWants, check_wants,
  1042. [b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'],
  1043. {b'refs/heads/blah': b'3f3dc7a53fb752a6961d3a56683df46d4d3bf262',
  1044. b'refs/heads/blah^{}':
  1045. b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'})
  1046. class FetchPackResultTests(TestCase):
  1047. def test_eq(self):
  1048. self.assertEqual(
  1049. FetchPackResult(
  1050. {b'refs/heads/master':
  1051. b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}, {},
  1052. b'user/agent'),
  1053. FetchPackResult(
  1054. {b'refs/heads/master':
  1055. b'2f3dc7a53fb752a6961d3a56683df46d4d3bf262'}, {},
  1056. b'user/agent'))