test_client.py 16 KB

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