test_client.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. map(lambda r: dest.refs.set_if_equals(r[0], None, r[1]), refs.items())
  160. self.assertDestEqualsSrc()
  161. def test_incremental_fetch_pack(self):
  162. self.test_fetch_pack()
  163. dest, dummy = self.disable_ff_and_make_dummy_commit()
  164. dest.refs['refs/heads/master'] = dummy
  165. c = self._client()
  166. dest = repo.Repo(os.path.join(self.gitroot, 'server_new.export'))
  167. refs = c.fetch(self._build_path('/dest'), dest)
  168. map(lambda r: dest.refs.set_if_equals(r[0], None, r[1]), refs.items())
  169. self.assertDestEqualsSrc()
  170. def test_fetch_pack_no_side_band_64k(self):
  171. c = self._client()
  172. c._fetch_capabilities.remove('side-band-64k')
  173. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  174. refs = c.fetch(self._build_path('/server_new.export'), dest)
  175. map(lambda r: dest.refs.set_if_equals(r[0], None, r[1]), refs.items())
  176. self.assertDestEqualsSrc()
  177. def test_fetch_pack_zero_sha(self):
  178. # zero sha1s are already present on the client, and should
  179. # be ignored
  180. c = self._client()
  181. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  182. refs = c.fetch(self._build_path('/server_new.export'), dest,
  183. lambda refs: [protocol.ZERO_SHA])
  184. map(lambda r: dest.refs.set_if_equals(r[0], None, r[1]), refs.items())
  185. def test_send_remove_branch(self):
  186. dest = repo.Repo(os.path.join(self.gitroot, 'dest'))
  187. dummy_commit = self.make_dummy_commit(dest)
  188. dest.refs['refs/heads/master'] = dummy_commit
  189. dest.refs['refs/heads/abranch'] = dummy_commit
  190. sendrefs = dict(dest.refs)
  191. sendrefs['refs/heads/abranch'] = "00" * 20
  192. del sendrefs['HEAD']
  193. gen_pack = lambda have, want: []
  194. c = self._client()
  195. self.assertEqual(dest.refs["refs/heads/abranch"], dummy_commit)
  196. c.send_pack(self._build_path('/dest'), lambda _: sendrefs, gen_pack)
  197. self.assertFalse("refs/heads/abranch" in dest.refs)
  198. class DulwichTCPClientTest(CompatTestCase, DulwichClientTestBase):
  199. def setUp(self):
  200. CompatTestCase.setUp(self)
  201. DulwichClientTestBase.setUp(self)
  202. if check_for_daemon(limit=1):
  203. raise SkipTest('git-daemon was already running on port %s' %
  204. protocol.TCP_GIT_PORT)
  205. fd, self.pidfile = tempfile.mkstemp(prefix='dulwich-test-git-client',
  206. suffix=".pid")
  207. os.fdopen(fd).close()
  208. run_git_or_fail(
  209. ['daemon', '--verbose', '--export-all',
  210. '--pid-file=%s' % self.pidfile, '--base-path=%s' % self.gitroot,
  211. '--detach', '--reuseaddr', '--enable=receive-pack',
  212. '--enable=upload-archive', '--listen=localhost', self.gitroot], cwd=self.gitroot)
  213. if not check_for_daemon():
  214. raise SkipTest('git-daemon failed to start')
  215. def tearDown(self):
  216. try:
  217. os.kill(int(open(self.pidfile).read().strip()), signal.SIGKILL)
  218. os.unlink(self.pidfile)
  219. except (OSError, IOError):
  220. pass
  221. DulwichClientTestBase.tearDown(self)
  222. CompatTestCase.tearDown(self)
  223. def _client(self):
  224. return client.TCPGitClient('localhost')
  225. def _build_path(self, path):
  226. return path
  227. class TestSSHVendor(object):
  228. @staticmethod
  229. def run_command(host, command, username=None, port=None):
  230. cmd, path = command[0].replace("'", '').split(' ')
  231. cmd = cmd.split('-', 1)
  232. p = subprocess.Popen(cmd + [path], env=get_safe_env(), stdin=subprocess.PIPE,
  233. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  234. return client.SubprocessWrapper(p)
  235. class DulwichMockSSHClientTest(CompatTestCase, DulwichClientTestBase):
  236. def setUp(self):
  237. CompatTestCase.setUp(self)
  238. DulwichClientTestBase.setUp(self)
  239. self.real_vendor = client.get_ssh_vendor
  240. client.get_ssh_vendor = TestSSHVendor
  241. def tearDown(self):
  242. DulwichClientTestBase.tearDown(self)
  243. CompatTestCase.tearDown(self)
  244. client.get_ssh_vendor = self.real_vendor
  245. def _client(self):
  246. return client.SSHGitClient('localhost')
  247. def _build_path(self, path):
  248. return self.gitroot + path
  249. class DulwichSubprocessClientTest(CompatTestCase, DulwichClientTestBase):
  250. def setUp(self):
  251. CompatTestCase.setUp(self)
  252. DulwichClientTestBase.setUp(self)
  253. def tearDown(self):
  254. DulwichClientTestBase.tearDown(self)
  255. CompatTestCase.tearDown(self)
  256. def _client(self):
  257. return client.SubprocessGitClient(stderr=subprocess.PIPE)
  258. def _build_path(self, path):
  259. return self.gitroot + path
  260. class GitHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  261. """HTTP Request handler that calls out to 'git http-backend'."""
  262. # Make rfile unbuffered -- we need to read one line and then pass
  263. # the rest to a subprocess, so we can't use buffered input.
  264. rbufsize = 0
  265. def do_POST(self):
  266. self.run_backend()
  267. def do_GET(self):
  268. self.run_backend()
  269. def send_head(self):
  270. return self.run_backend()
  271. def log_request(self, code='-', size='-'):
  272. # Let's be quiet, the test suite is noisy enough already
  273. pass
  274. def run_backend(self):
  275. """Call out to git http-backend."""
  276. # Based on CGIHTTPServer.CGIHTTPRequestHandler.run_cgi:
  277. # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved
  278. # Licensed under the Python Software Foundation License.
  279. rest = self.path
  280. # find an explicit query string, if present.
  281. i = rest.rfind('?')
  282. if i >= 0:
  283. rest, query = rest[:i], rest[i+1:]
  284. else:
  285. query = ''
  286. env = copy.deepcopy(os.environ)
  287. env['SERVER_SOFTWARE'] = self.version_string()
  288. env['SERVER_NAME'] = self.server.server_name
  289. env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  290. env['SERVER_PROTOCOL'] = self.protocol_version
  291. env['SERVER_PORT'] = str(self.server.server_port)
  292. env['GIT_PROJECT_ROOT'] = self.server.root_path
  293. env["GIT_HTTP_EXPORT_ALL"] = "1"
  294. env['REQUEST_METHOD'] = self.command
  295. uqrest = urllib.unquote(rest)
  296. env['PATH_INFO'] = uqrest
  297. env['SCRIPT_NAME'] = "/"
  298. if query:
  299. env['QUERY_STRING'] = query
  300. host = self.address_string()
  301. if host != self.client_address[0]:
  302. env['REMOTE_HOST'] = host
  303. env['REMOTE_ADDR'] = self.client_address[0]
  304. authorization = self.headers.getheader("authorization")
  305. if authorization:
  306. authorization = authorization.split()
  307. if len(authorization) == 2:
  308. import base64, binascii
  309. env['AUTH_TYPE'] = authorization[0]
  310. if authorization[0].lower() == "basic":
  311. try:
  312. authorization = base64.decodestring(authorization[1])
  313. except binascii.Error:
  314. pass
  315. else:
  316. authorization = authorization.split(':')
  317. if len(authorization) == 2:
  318. env['REMOTE_USER'] = authorization[0]
  319. # XXX REMOTE_IDENT
  320. if self.headers.typeheader is None:
  321. env['CONTENT_TYPE'] = self.headers.type
  322. else:
  323. env['CONTENT_TYPE'] = self.headers.typeheader
  324. length = self.headers.getheader('content-length')
  325. if length:
  326. env['CONTENT_LENGTH'] = length
  327. referer = self.headers.getheader('referer')
  328. if referer:
  329. env['HTTP_REFERER'] = referer
  330. accept = []
  331. for line in self.headers.getallmatchingheaders('accept'):
  332. if line[:1] in "\t\n\r ":
  333. accept.append(line.strip())
  334. else:
  335. accept = accept + line[7:].split(',')
  336. env['HTTP_ACCEPT'] = ','.join(accept)
  337. ua = self.headers.getheader('user-agent')
  338. if ua:
  339. env['HTTP_USER_AGENT'] = ua
  340. co = filter(None, self.headers.getheaders('cookie'))
  341. if co:
  342. env['HTTP_COOKIE'] = ', '.join(co)
  343. # XXX Other HTTP_* headers
  344. # Since we're setting the env in the parent, provide empty
  345. # values to override previously set values
  346. for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
  347. 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
  348. env.setdefault(k, "")
  349. self.send_response(200, "Script output follows")
  350. decoded_query = query.replace('+', ' ')
  351. try:
  352. nbytes = int(length)
  353. except (TypeError, ValueError):
  354. nbytes = 0
  355. if self.command.lower() == "post" and nbytes > 0:
  356. data = self.rfile.read(nbytes)
  357. else:
  358. data = None
  359. # throw away additional data [see bug #427345]
  360. while select.select([self.rfile._sock], [], [], 0)[0]:
  361. if not self.rfile._sock.recv(1):
  362. break
  363. args = ['http-backend']
  364. if '=' not in decoded_query:
  365. args.append(decoded_query)
  366. stdout = run_git_or_fail(args, input=data, env=env, stderr=subprocess.PIPE)
  367. self.wfile.write(stdout)
  368. class HTTPGitServer(BaseHTTPServer.HTTPServer):
  369. allow_reuse_address = True
  370. def __init__(self, server_address, root_path):
  371. BaseHTTPServer.HTTPServer.__init__(self, server_address, GitHTTPRequestHandler)
  372. self.root_path = root_path
  373. self.server_name = "localhost"
  374. def get_url(self):
  375. return 'http://%s:%s/' % (self.server_name, self.server_port)
  376. class DulwichHttpClientTest(CompatTestCase, DulwichClientTestBase):
  377. min_git_version = (1, 7, 0, 2)
  378. def setUp(self):
  379. CompatTestCase.setUp(self)
  380. DulwichClientTestBase.setUp(self)
  381. self._httpd = HTTPGitServer(("localhost", 0), self.gitroot)
  382. self.addCleanup(self._httpd.shutdown)
  383. threading.Thread(target=self._httpd.serve_forever).start()
  384. run_git_or_fail(['config', 'http.uploadpack', 'true'],
  385. cwd=self.dest)
  386. run_git_or_fail(['config', 'http.receivepack', 'true'],
  387. cwd=self.dest)
  388. def tearDown(self):
  389. DulwichClientTestBase.tearDown(self)
  390. CompatTestCase.tearDown(self)
  391. def _client(self):
  392. return client.HttpGitClient(self._httpd.get_url())
  393. def _build_path(self, path):
  394. return path
  395. def test_archive(self):
  396. raise SkipTest("exporting archives not supported over http")