test_client.py 47 KB

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