test_client.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. # test_client.py -- Compatibilty tests for git client.
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) any later version of
  8. # the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Compatibilty tests between the Dulwich client and the cgit server."""
  20. from io import BytesIO
  21. import BaseHTTPServer
  22. import SimpleHTTPServer
  23. import copy
  24. import os
  25. import select
  26. import shutil
  27. import signal
  28. import subprocess
  29. import tarfile
  30. import tempfile
  31. import threading
  32. import urllib
  33. from dulwich import (
  34. client,
  35. errors,
  36. file,
  37. index,
  38. protocol,
  39. objects,
  40. repo,
  41. )
  42. from dulwich.tests import (
  43. get_safe_env,
  44. SkipTest,
  45. )
  46. from dulwich.tests.compat.utils import (
  47. CompatTestCase,
  48. check_for_daemon,
  49. import_repo_to_dir,
  50. run_git_or_fail,
  51. )
  52. class DulwichClientTestBase(object):
  53. """Tests for client/server compatibility."""
  54. def setUp(self):
  55. self.gitroot = os.path.dirname(import_repo_to_dir('server_new.export'))
  56. self.dest = os.path.join(self.gitroot, 'dest')
  57. file.ensure_dir_exists(self.dest)
  58. run_git_or_fail(['init', '--quiet', '--bare'], cwd=self.dest)
  59. def tearDown(self):
  60. shutil.rmtree(self.gitroot)
  61. def assertDestEqualsSrc(self):
  62. src = repo.Repo(os.path.join(self.gitroot, 'server_new.export'))
  63. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  64. self.assertReposEqual(src, dest)
  65. def _client(self):
  66. raise NotImplementedError()
  67. def _build_path(self):
  68. raise NotImplementedError()
  69. def _do_send_pack(self):
  70. c = self._client()
  71. srcpath = os.path.join(self.gitroot, 'server_new.export')
  72. src = repo.Repo(srcpath)
  73. sendrefs = dict(src.get_refs())
  74. del sendrefs['HEAD']
  75. c.send_pack(self._build_path('/dest'), lambda _: sendrefs,
  76. src.object_store.generate_pack_contents)
  77. def test_send_pack(self):
  78. self._do_send_pack()
  79. self.assertDestEqualsSrc()
  80. def test_send_pack_nothing_to_send(self):
  81. self._do_send_pack()
  82. self.assertDestEqualsSrc()
  83. # nothing to send, but shouldn't raise either.
  84. self._do_send_pack()
  85. def test_send_without_report_status(self):
  86. c = self._client()
  87. c._send_capabilities.remove('report-status')
  88. srcpath = os.path.join(self.gitroot, 'server_new.export')
  89. src = repo.Repo(srcpath)
  90. sendrefs = dict(src.get_refs())
  91. del sendrefs['HEAD']
  92. c.send_pack(self._build_path('/dest'), lambda _: sendrefs,
  93. src.object_store.generate_pack_contents)
  94. self.assertDestEqualsSrc()
  95. def make_dummy_commit(self, dest):
  96. b = objects.Blob.from_string('hi')
  97. dest.object_store.add_object(b)
  98. t = index.commit_tree(dest.object_store, [('hi', b.id, 0o100644)])
  99. c = objects.Commit()
  100. c.author = c.committer = 'Foo Bar <foo@example.com>'
  101. c.author_time = c.commit_time = 0
  102. c.author_timezone = c.commit_timezone = 0
  103. c.message = 'hi'
  104. c.tree = t
  105. dest.object_store.add_object(c)
  106. return c.id
  107. def disable_ff_and_make_dummy_commit(self):
  108. # disable non-fast-forward pushes to the server
  109. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  110. run_git_or_fail(['config', 'receive.denyNonFastForwards', 'true'],
  111. cwd=dest.path)
  112. commit_id = self.make_dummy_commit(dest)
  113. return dest, commit_id
  114. def compute_send(self):
  115. srcpath = os.path.join(self.gitroot, 'server_new.export')
  116. src = repo.Repo(srcpath)
  117. sendrefs = dict(src.get_refs())
  118. del sendrefs['HEAD']
  119. return sendrefs, src.object_store.generate_pack_contents
  120. def test_send_pack_one_error(self):
  121. dest, dummy_commit = self.disable_ff_and_make_dummy_commit()
  122. dest.refs['refs/heads/master'] = dummy_commit
  123. sendrefs, gen_pack = self.compute_send()
  124. c = self._client()
  125. try:
  126. c.send_pack(self._build_path('/dest'), lambda _: sendrefs, gen_pack)
  127. except errors.UpdateRefsError as e:
  128. self.assertEqual('refs/heads/master failed to update', str(e))
  129. self.assertEqual({'refs/heads/branch': 'ok',
  130. 'refs/heads/master': 'non-fast-forward'},
  131. e.ref_status)
  132. def test_send_pack_multiple_errors(self):
  133. dest, dummy = self.disable_ff_and_make_dummy_commit()
  134. # set up for two non-ff errors
  135. branch, master = 'refs/heads/branch', 'refs/heads/master'
  136. dest.refs[branch] = dest.refs[master] = dummy
  137. sendrefs, gen_pack = self.compute_send()
  138. c = self._client()
  139. try:
  140. c.send_pack(self._build_path('/dest'), lambda _: sendrefs, gen_pack)
  141. except errors.UpdateRefsError as e:
  142. self.assertIn(str(e),
  143. ['{0}, {1} failed to update'.format(branch, master),
  144. '{1}, {0} failed to update'.format(branch, master)])
  145. self.assertEqual({branch: 'non-fast-forward',
  146. master: 'non-fast-forward'},
  147. e.ref_status)
  148. def test_archive(self):
  149. c = self._client()
  150. f = BytesIO()
  151. c.archive(self._build_path('/server_new.export'), 'HEAD', f.write)
  152. f.seek(0)
  153. tf = tarfile.open(fileobj=f)
  154. self.assertEqual(['baz', 'foo'], tf.getnames())
  155. def test_fetch_pack(self):
  156. c = self._client()
  157. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  158. refs = c.fetch(self._build_path('/server_new.export'), dest)
  159. for r in refs.items():
  160. dest.refs.set_if_equals(r[0], None, r[1])
  161. self.assertDestEqualsSrc()
  162. def test_incremental_fetch_pack(self):
  163. self.test_fetch_pack()
  164. dest, dummy = self.disable_ff_and_make_dummy_commit()
  165. dest.refs['refs/heads/master'] = dummy
  166. c = self._client()
  167. dest = repo.Repo(os.path.join(self.gitroot, 'server_new.export'))
  168. refs = c.fetch(self._build_path('/dest'), dest)
  169. for r in refs.items():
  170. dest.refs.set_if_equals(r[0], None, r[1])
  171. self.assertDestEqualsSrc()
  172. def test_fetch_pack_no_side_band_64k(self):
  173. c = self._client()
  174. c._fetch_capabilities.remove('side-band-64k')
  175. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  176. refs = c.fetch(self._build_path('/server_new.export'), dest)
  177. for r in refs.items():
  178. dest.refs.set_if_equals(r[0], None, r[1])
  179. self.assertDestEqualsSrc()
  180. def test_fetch_pack_zero_sha(self):
  181. # zero sha1s are already present on the client, and should
  182. # be ignored
  183. c = self._client()
  184. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  185. refs = c.fetch(self._build_path('/server_new.export'), dest,
  186. lambda refs: [protocol.ZERO_SHA])
  187. map(lambda r: dest.refs.set_if_equals(r[0], None, r[1]), refs.items())
  188. def test_send_remove_branch(self):
  189. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  190. dummy_commit = self.make_dummy_commit(dest)
  191. dest.refs['refs/heads/master'] = dummy_commit
  192. dest.refs['refs/heads/abranch'] = dummy_commit
  193. sendrefs = dict(dest.refs)
  194. sendrefs['refs/heads/abranch'] = "00" * 20
  195. del sendrefs['HEAD']
  196. gen_pack = lambda have, want: []
  197. c = self._client()
  198. self.assertEqual(dest.refs["refs/heads/abranch"], dummy_commit)
  199. c.send_pack(self._build_path('/dest'), lambda _: sendrefs, gen_pack)
  200. self.assertFalse("refs/heads/abranch" in dest.refs)
  201. class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase):
  202. def setUp(self):
  203. CompatTestCase.setUp(self)
  204. DulwichClientTestBase.setUp(self)
  205. if check_for_daemon(limit=1):
  206. raise SkipTest('git-daemon was already running on port %s' %
  207. protocol.TCP_GIT_PORT)
  208. fd, self.pidfile = tempfile.mkstemp(prefix='dulwich-test-git-client',
  209. suffix=".pid")
  210. os.fdopen(fd).close()
  211. run_git_or_fail(
  212. ['daemon', '--verbose', '--export-all',
  213. '--pid-file=%s' % self.pidfile, '--base-path=%s' % self.gitroot,
  214. '--detach', '--reuseaddr', '--enable=receive-pack',
  215. '--enable=upload-archive', '--listen=localhost', self.gitroot], cwd=self.gitroot)
  216. if not check_for_daemon():
  217. raise SkipTest('git-daemon failed to start')
  218. def tearDown(self):
  219. try:
  220. os.kill(int(open(self.pidfile).read().strip()), signal.SIGKILL)
  221. os.unlink(self.pidfile)
  222. except (OSError, IOError):
  223. pass
  224. DulwichClientTestBase.tearDown(self)
  225. CompatTestCase.tearDown(self)
  226. def _client(self):
  227. return client.TCPGitClient('localhost')
  228. def _build_path(self, path):
  229. return path
  230. class TestSSHVendor(object):
  231. @staticmethod
  232. def run_command(host, command, username=None, port=None):
  233. cmd, path = command[0].replace("'", '').split(' ')
  234. cmd = cmd.split('-', 1)
  235. p = subprocess.Popen(cmd + [path], env=get_safe_env(), stdin=subprocess.PIPE,
  236. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  237. return client.SubprocessWrapper(p)
  238. class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase):
  239. def setUp(self):
  240. CompatTestCase.setUp(self)
  241. DulwichClientTestBase.setUp(self)
  242. self.real_vendor = client.get_ssh_vendor
  243. client.get_ssh_vendor = TestSSHVendor
  244. def tearDown(self):
  245. DulwichClientTestBase.tearDown(self)
  246. CompatTestCase.tearDown(self)
  247. client.get_ssh_vendor = self.real_vendor
  248. def _client(self):
  249. return client.SSHGitClient('localhost')
  250. def _build_path(self, path):
  251. return self.gitroot + path
  252. class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase):
  253. def setUp(self):
  254. CompatTestCase.setUp(self)
  255. DulwichClientTestBase.setUp(self)
  256. def tearDown(self):
  257. DulwichClientTestBase.tearDown(self)
  258. CompatTestCase.tearDown(self)
  259. def _client(self):
  260. return client.SubprocessGitClient(stderr=subprocess.PIPE)
  261. def _build_path(self, path):
  262. return self.gitroot + path
  263. class GitHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  264. """HTTP Request handler that calls out to 'git http-backend'."""
  265. # Make rfile unbuffered -- we need to read one line and then pass
  266. # the rest to a subprocess, so we can't use buffered input.
  267. rbufsize = 0
  268. def do_POST(self):
  269. self.run_backend()
  270. def do_GET(self):
  271. self.run_backend()
  272. def send_head(self):
  273. return self.run_backend()
  274. def log_request(self, code='-', size='-'):
  275. # Let's be quiet, the test suite is noisy enough already
  276. pass
  277. def run_backend(self):
  278. """Call out to git http-backend."""
  279. # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:
  280. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  281. # Licensed under the Python Software Foundation License.
  282. rest = self.path
  283. # find an explicit query string, if present.
  284. i = rest.rfind('?')
  285. if i >= 0:
  286. rest, query = rest[:i], rest[i+1:]
  287. else:
  288. query = ''
  289. env = copy.deepcopy(os.environ)
  290. env['SERVER_SOFTWARE'] = self.version_string()
  291. env['SERVER_NAME'] = self.server.server_name
  292. env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  293. env['SERVER_PROTOCOL'] = self.protocol_version
  294. env['SERVER_PORT'] = str(self.server.server_port)
  295. env['GIT_PROJECT_ROOT'] = self.server.root_path
  296. env["GIT_HTTP_EXPORT_ALL"] = "1"
  297. env['REQUEST_METHOD'] = self.command
  298. uqrest = urllib.unquote(rest)
  299. env['PATH_INFO'] = uqrest
  300. env['SCRIPT_NAME'] = "/"
  301. if query:
  302. env['QUERY_STRING'] = query
  303. host = self.address_string()
  304. if host != self.client_address[0]:
  305. env['REMOTE_HOST'] = host
  306. env['REMOTE_ADDR'] = self.client_address[0]
  307. authorization = self.headers.getheader("authorization")
  308. if authorization:
  309. authorization = authorization.split()
  310. if len(authorization) == 2:
  311. import base64, binascii
  312. env['AUTH_TYPE'] = authorization[0]
  313. if authorization[0].lower() == "basic":
  314. try:
  315. authorization = base64.decodestring(authorization[1])
  316. except binascii.Error:
  317. pass
  318. else:
  319. authorization = authorization.split(':')
  320. if len(authorization) == 2:
  321. env['REMOTE_USER'] = authorization[0]
  322. # XXX REMOTE_IDENT
  323. if self.headers.typeheader is None:
  324. env['CONTENT_TYPE'] = self.headers.type
  325. else:
  326. env['CONTENT_TYPE'] = self.headers.typeheader
  327. length = self.headers.getheader('content-length')
  328. if length:
  329. env['CONTENT_LENGTH'] = length
  330. referer = self.headers.getheader('referer')
  331. if referer:
  332. env['HTTP_REFERER'] = referer
  333. accept = []
  334. for line in self.headers.getallmatchingheaders('accept'):
  335. if line[:1] in "\t\n\r ":
  336. accept.append(line.strip())
  337. else:
  338. accept = accept + line[7:].split(',')
  339. env['HTTP_ACCEPT'] = ','.join(accept)
  340. ua = self.headers.getheader('user-agent')
  341. if ua:
  342. env['HTTP_USER_AGENT'] = ua
  343. co = filter(None, self.headers.getheaders('cookie'))
  344. if co:
  345. env['HTTP_COOKIE'] = ', '.join(co)
  346. # XXX Other HTTP_* headers
  347. # Since we're setting the env in the parent, provide empty
  348. # values to override previously set values
  349. for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
  350. 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
  351. env.setdefault(k, "")
  352. self.send_response(200, "Script output follows")
  353. decoded_query = query.replace('+', ' ')
  354. try:
  355. nbytes = int(length)
  356. except (TypeError, ValueError):
  357. nbytes = 0
  358. if self.command.lower() == "post" and nbytes > 0:
  359. data = self.rfile.read(nbytes)
  360. else:
  361. data = None
  362. # throw away additional data [see bug #427345]
  363. while select.select([self.rfile._sock], [], [], 0)[0]:
  364. if not self.rfile._sock.recv(1):
  365. break
  366. args = ['http-backend']
  367. if '=' not in decoded_query:
  368. args.append(decoded_query)
  369. stdout = run_git_or_fail(args, input=data, env=env, stderr=subprocess.PIPE)
  370. self.wfile.write(stdout)
  371. class HTTPGitServer(BaseHTTPServer.HTTPServer):
  372. allow_reuse_address = True
  373. def __init__(self, server_address, root_path):
  374. BaseHTTPServer.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler)
  375. self.root_path = root_path
  376. self.server_name = "localhost"
  377. def get_url(self):
  378. return 'http://%s:%s/' % (self.server_name, self.server_port)
  379. class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase):
  380. min_git_version = (1, 7, 0, 2)
  381. def setUp(self):
  382. CompatTestCase.setUp(self)
  383. DulwichClientTestBase.setUp(self)
  384. self._httpd = HTTPGitServer(("localhost", 0), self.gitroot)
  385. self.addCleanup(self._httpd.shutdown)
  386. threading.Thread(target=self._httpd.serve_forever).start()
  387. run_git_or_fail(['config', 'http.uploadpack', 'true'],
  388. cwd=self.dest)
  389. run_git_or_fail(['config', 'http.receivepack', 'true'],
  390. cwd=self.dest)
  391. def tearDown(self):
  392. DulwichClientTestBase.tearDown(self)
  393. CompatTestCase.tearDown(self)
  394. def _client(self):
  395. return client.HttpGitClient(self._httpd.get_url())
  396. def _build_path(self, path):
  397. return path
  398. def test_archive(self):
  399. raise SkipTest("exporting archives not supported over http")