test_client.py 46 KB

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