test_client.py 17 KB

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