test_client.py 53 KB

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