test_client.py 17 KB

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